How to capture browser close event?

2019-01-06 21:03发布

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.

4条回答
Rolldiameter
2楼-- · 2019-01-06 21:14
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;
  }
};
查看更多
我只想做你的唯一
3楼-- · 2019-01-06 21:18

Attach a handler to the unload event.

查看更多
劳资没心,怎么记你
4楼-- · 2019-01-06 21:24

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> 
查看更多
Summer. ? 凉城
5楼-- · 2019-01-06 21:36

Use the beforeunload event.

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.

查看更多
登录 后发表回答