iOS Safari 回退导致 alert 失效
我在文章页增加了解析运行 html 和 js 源码的功能。然后发现一个诡异的问题,在手机端 Safari 按回退和前进键会导致 alert 失效。验证了电脑端和手机端各种浏览器,仅手机端 Safari 复现这个问题。
我查到的解释是:
alert/confirm/prompt dialogs will not be displayed if the user has navigated back to a pushState location. Once a user has navigated back (at any point), calling alert(…), confirm(…), or prompt(…) will not display dialog boxes. confirm(…) will always return false, and prompt(…) will return null.
进一步查找解决办法,实践后均无效。最后只能放弃 alert,自己写弹层来实现。
原代码:
<div style="display:flex;justify-content:center">
<button onclick="alert('爽!!!')" style="width:50%">查看作者精神状态</button>
</div>
修改后:
<style>
.modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}
.content {
padding: 20px;
background-color: #fff;
border-radius: 5px;
width: 300px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
text-align: center
}
.text {
font-size: 36px;
margin: 0 0 20px;
color: #000;
}
.button {
float: right;
color: #fff;
}
</style>
<div style="display:flex;justify-content:center">
<button onclick="customAlert('爽!!!')" style="width:50%">查看作者精神状态</button>
</div>
function customAlert(message) {
var modal = document.createElement('div');
modal.className = 'modal';
var content = document.createElement('div');
content.className = 'content';
var messageText = document.createElement('p');
messageText.className = 'text';
messageText.textContent = message;
content.appendChild(messageText);
var closeButton = document.createElement('button');
closeButton.textContent = '知道了';
closeButton.className = 'button';
closeButton.onclick = function () {
modal.remove();
};
content.appendChild(closeButton);
modal.appendChild(content);
document.body.appendChild(modal);
}
其中,button 复用了全站样式。效果见《手开 Oracle ARM 4C24G》。
标签: 前端