[英]Can't make Chrome, Edge & Firefox to quietly execute beforeunload event
当用户单击当前页面上的其他链接引用并离开当前页面时,我想做一些事情。 我不想要任何确认提示 - 只是静默执行我的 function。根据规范和谷歌上的大量回复,为了没有这个确认提示,我根本不会在我的事件中有事件 preventDefault() 或 event.returnValue听众:
window.addEventListener("beforeunload", function(event) {
unloading_page_func();
}, false);
这样的代码在 Chrome 和 Edge 中运行良好,但 Mozilla 什么都不做——不确定它是否没有添加事件监听器或没有触发 beforeunload 事件:console.log 和 alert 在 beforeunload 期间都不起作用:(
我尝试了不同的组合:添加了 event.returnValue = '':
window.addEventListener("beforeunload", function(event) {
unloading_page_func();
event.returnValue = '';
}, false);
添加了 event.returnValue = null:
window.addEventListener("beforeunload", function(event) {
unloading_page_func();
event.returnValue = null;
}, false);
添加了 event.preventDefault():
window.addEventListener("beforeunload", function(event) {
unloading_page_func();
event.preventDefault();
}, false);
尝试了两者的不同组合,event.preventDefault() 和 event.returnValue - 始终是上面列出的结果之一。 关于如何让我的 Chrome(版本 92.0.4515.131)、Edge(版本 92.0.902.67)和 Firefox(版本 90.0.2)安静地执行我的 function 而不生成任何确认提示的任何建议?
正如“Bravo”评论的那样,我遇到的行为可能与 unloading_page_func() 的内容有关 我想在用户切换到另一个页面时响铃 - 这个 function 将这个事件监听器删除到“beforeunload”,清除 function 的间隔更新页面,并向完成某些清理的服务器发送 GET 请求:
function unloading_page_func()
{
try {
xmlHttp = new XMLHttpRequest();
}
catch (e) {
try {
xmlHttp = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (e) {
try {
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
}
catch (e) {
alert("This browser does not support AJAX!");
}
}
}
window.removeEventListener("beforeunload", unloading_page_func, false);
clearInterval(update_display_interval_id);
xmlHttp.open('GET', '/unload_page', true);
xmlHttp.send();
};
按照 Bravo 的建议使用“信标”解决了我的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.