Javascript 如何捕获浏览器关闭事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6622461/
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-23 22:30:42  来源:igfitidea点击:

How to capture browser close event?

javascriptjqueryeventsbrowser

提问by Lan

I want to capture the browser close event in my application and show a confirm box to user. I am using JSF 2.0 and richfaces 4.0.

我想在我的应用程序中捕获浏览器关闭事件并向用户显示一个确认框。我使用的是 JSF 2.0 和 Richfaces 4.0。

回答by Praveen Prasad

window.onbeforeunload = function () 
{
  var shallIAlertUser = Do_Whatever(); //get boolen value
  if (shallIAlertUser) {
    //this will alert user
    return 'Are you sure?';
  }
  else {
    //this wont
    window.onbeforeunload = undefined;
  }
};

回答by alex

Use the beforeunloadevent.

使用beforeunload事件。

window.onbeforeunload = function(event) {

    event = event || window.event;

    var confirmClose = 'Are you sure?';

    // For IE and Firefox prior to version 4
    if (event) {
       event.returnValue = confirmClose;
    }

    // For Safari
    return confirmClose;

}

Keep in mind this will be fire for other events besides closing the window, such as reloading and form submission.

请记住,除了关闭窗口外,其他事件也会触发,例如重新加载和表单提交。

回答by Jigar Joshi

onbeforeunload

onbeforeunload

< body onbeforeunload="alert('Closing');">

Example :

例子 :

<html> 
<head>
<title>`onbeforeunload` Event Demo</title>
</head>
<body onbeforeunload="return 'Are you sure you want to exit ?';">
</body> 
</html> 

回答by Aaron Digulla

Attach a handler to the unloadevent.

将处理程序附加到unload事件。