如何使用 jQuery 触发浏览器窗口或选项卡关闭事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17831683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:03:07  来源:igfitidea点击:

How to trigger a browser window or tab close event with jQuery

jquery

提问by Asce4s

Is there any way to trigger a window/tab close event with jQuery. I already tried with

有没有办法用 jQuery 触发窗口/选项卡关闭事件。我已经尝试过

$('selector').unload() 

But it didn't work.

但它没有用。

回答by mattytommo

You can use unload()on the windowproperty in jQuery:

您可以在 jQuery 中unload()window属性上使用:

$(window).unload(function() {
   //do stuff
});

You don't needjQuery to do it though, you can use good ol' fashioned JavaScript:

你并不需要jQuery来做到这一点,虽然,你可以用好醇”老式的JavaScript:

window.onbeforeunload = function(e){
    var msg = 'Are you sure?';
    e = e || window.event;

    if(e)
        e.returnValue = msg;

    return msg;
}

回答by Dilantha

Try this

尝试这个

$(window).unload(function() {  
        alert("Unload");  
});?

Note :some times dialogs are blocked in unload . You can check your console to make it confirm.

注意:有时对话框在卸载时被阻塞。您可以检查您的控制台以进行确认。

回答by kathir

In Javascript

在 JavaScript 中

window.onbeforeunload = function (event) {
    var message = 'Important: Please click on \'Save\' button to leave this page.';
    if (typeof event == 'undefined') {
        event = window.event;
    }
    if (event) {
        event.returnValue = message;
    }
    return message;
};

In jQuery

在 jQuery 中

$(window).on('beforeunload', function(){
      return 'Are you sure you want to leave?';
});