有没有办法在用户选择重新加载/关闭浏览器/退出页面之前执行某个功能?
我需要这个用于我想写的"在线/离线"状态功能.我想检测用户是否仍在页面上.
有任何想法吗?:)
也许有更好的方法呢?
Sam*_*iew 20
内联功能:
window.onbeforeunload = function(evt) {
// Cancel the event (if necessary)
evt.preventDefault();
// Google Chrome requires returnValue to be set
evt.returnValue = '';
return null;
};
Run Code Online (Sandbox Code Playgroud)
或通过事件监听器(推荐):
window.addEventListener("beforeunload", function(evt) {
// Cancel the event (if necessary)
evt.preventDefault();
// Google Chrome requires returnValue to be set
evt.returnValue = '';
return null;
});
Run Code Online (Sandbox Code Playgroud)
或者如果你有jQuery:
$(window).on("beforeunload", function(evt) {
// Cancel the event (if necessary)
evt.preventDefault();
// Google Chrome requires returnValue to be set
evt.returnValue = '';
return null;
});
Run Code Online (Sandbox Code Playgroud)
笔记:
当此事件返回非void值时,将提示用户确认页面卸载.在大多数浏览器中,事件的返回值显示在此对话框中.
自2011年5月25日起,HTML5规范声明在此事件期间可能会忽略对window.showModalDialog(),window.alert(),window.confirm()和window.prompt()方法的调用.
请参阅https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload上的文档