在浏览器重新加载/关闭浏览器/退出页面之前执行Javascript功能?

问题描述:

有没有办法在用户选择重新加载/关闭浏览器/退出页面之前执行某个功能?

Is there a way to execute a function before a user chooses to reload/close browser/exit page?

我需要这个以获得在线/离线状态功能我想写。我想检测用户是否仍然在页面上。

I need this for an "online/offline" status function i am trying to write. I want to detect whether the user is still on the page or not.

任何想法? :)

也许有更好的方法吗?

内联函数:

window.onbeforeunload = function(evt) {

    // Cancel the event (if necessary)
    evt.preventDefault();

    // Google Chrome requires returnValue to be set
    evt.returnValue = '';

    return null;
};

或通过事件监听器(推荐):

or via an event listener (recommended):

window.addEventListener("beforeunload", function(evt) {

    // Cancel the event (if necessary)
    evt.preventDefault();

    // Google Chrome requires returnValue to be set
    evt.returnValue = '';

    return null;
});

或者如果你有jQuery:

or if you have jQuery:

$(window).on("beforeunload", function(evt) {

    // Cancel the event (if necessary)
    evt.preventDefault();

    // Google Chrome requires returnValue to be set
    evt.returnValue = '';

    return null;
});

注意:


当此事件返回非void值时,系统会提示用户
确认页面卸载。在大多数浏览器中,
事件的返回值显示在此对话框中。

When this event returns a non-void value, the user is prompted to confirm the page unload. In most browsers, the return value of the event is displayed in this dialog.

自2011年5月25日起,HTML5规范声明调用
window.showModalDialog(),window.alert(),window.confirm()和
window.prompt()方法在此事件中可能会被忽略。

Since 25 May 2011, the HTML5 specification states that calls to window.showModalDialog(), window.alert(), window.confirm() and window.prompt() methods may be ignored during this event.

请参阅 https中的文档: //developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload