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

9

有没有一种方法在用户选择重新加载/关闭浏览器/退出页面之前执行函数?

我需要这个功能来编写一个“在线/离线”状态函数。我想检测用户是否仍然在页面上。

有什么想法吗? :)

也许有更好的方法?


window.onbeforeunload = function () {...} 窗口.在卸载前 = 函数 () {...} - Moritz Roessler
2
window.onbeforeunload,参考:https://developer.mozilla.org/zh-CN/docs/DOM/window.onbeforeunload - PatrikAkerstrand
3个回答

23

内联函数:

window.onbeforeunload = function(evt) {

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

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

    return null;
};

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

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

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

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

    return null;
});

或者如果你已经使用了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()方法的调用可能会被忽略。

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


0

试试这个:

$( window ).unload(function() {
  alert( "Handler for .unload() called." );
});

或者如果您想要确认警报,则使用此代码

<script>
window.onbeforeunload = function(e) {  
   return 'Your dialog message';
};
</script>

类型错误:$(...).unload 不是一个函数。 - john k


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接