
chrome 浏览器 onbeforeunload 事件不触发,如何替代?
在使用 chrome 浏览器实现页面离开提示时,onbeforeunload 事件可能无法正常触发,这是因为该事件已在 chrome 51 中被移除。
替代方案:
-
使用 beforeunload 事件:
beforeunload 事件在 chrome、firefox 和 safari 等浏览器中仍然可用,其功能类似于 onbeforeunload 事件,可以在用户离开页面之前触发。 -
使用 confirm() 方法:
可以在窗口关闭时使用 confirm() 方法向用户提示是否离开页面,如果用户点击“确定”,则允许关闭窗口。
示例代码:
使用 beforeunload 事件:
window.addeventlistener('beforeunload', function (e) {
var message = 'leave?';
e = e || window.event;
if (e) {
e.returnvalue = message;
}
return message;
});使用 confirm() 方法:
window.onbeforeunload = function () {
return confirm('leave?');
};以上替代方案可用于在 chrome 浏览器中实现页面离开提示。










