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

15

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

4个回答

17
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;
  }
};

6
使用 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;

}

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


1
关闭浏览器的方式有多种,包括使用Alt-F4、关闭选项卡或点击X按钮,还可以使用F5键进行页面刷新和重新加载。 - Kiquenet

5

onbeforeunload

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

例子:

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

beforeunload事件的目的是返回一个字符串。文档 - alex
@Alex 谢谢信息。OP只想要一个函数调用。 - jmj

1

将事件处理程序绑定到 unload 事件。


我尝试使用onbeforeunload事件。但问题是当我刷新页面或进行任何表单提交时,它也会调用onbeforeunload事件。 - Lan
无法区分它们之间的差异;浏览器只能告诉您当前文档即将被替换。这并不能让您了解为什么 - Aaron Digulla

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