在浏览器重新加载/关闭浏览器/退出页面之前执行Javascript功能? [英] Execute Javascript function before browser reloads/closes browser/exits page?

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆