我为onbeforeunload编写了一段代码。它适用于 IE,但不适用于任何其他浏览器。
var unloadFunction = function(){return "";}
window.addEventListener('beforeunload', unloadFunction);
这段代码可能会出什么问题。 :( 我无法理解。我希望它在所有浏览器中都能工作,以便在页面存在之前向用户显示确认弹出窗口。
最佳答案
由于网页行为不良,卸载前处理已被修改。因此,浏览器在卸载事件处理期间可能会也可能不会抑制警报。
引用MDN有关详细信息,但请注意提到的 returnValue
是事件对象的属性,而不是从事件处理函数返回的值。
下面的示例在主要浏览器和 IE 中运行(至少适用于 Windows 10)。
- Firefox 和 IE 报告了
event.returnValue
中提供的消息。 - Chrome 忽略了该消息,只是询问
Leave site?
Changes that you made may not be saved. - 仅 IE 显示警报框。
var unloadFunction = function( event){
event.returnValue = "do you really want to leave this page";
alert("unloading");
};
window.addEventListener('beforeunload', unloadFunction);
关于javascript - Onbeforeunload 不适用于 Chrome/Firefox,但适用于 IE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51643357/