问题解决的途径是使用通用事件模型(UEM)标准化beforeunload事件,并调用event.preventDefault()方法。在这个操作中,由于许多浏览器现在不允许自定义提示框,所以不能直接使用window.showModalDialog方法,而需要使用window.open方法来打开新的模态窗口。以下是一个示例代码,用于解决beforeunload事件后确认对话框未弹出的问题。
HTML代码:
Click the link below to trigger the beforeunload event:
TestJS代码:
window.addEventListener("beforeunload", function(e) { var confirmationMessage = "\o/"; (e || window.event).returnValue = confirmationMessage; //兼容 Gecko + IE setTimeout(function() { //在Firefox中必须使用异步延迟 callback(confirmationMessage); }, 0); });
function callback(msg) { alert("callback appears after leaving page: " + msg); }