本文介绍了在浏览器重新加载/关闭浏览器/退出页面之前执行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;
});

注意:

自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.

请参阅

这篇关于在浏览器重新加载/关闭浏览器/退出页面之前执行Javascript功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 11:05
查看更多