简体   繁体   中英

How to capture browser close event?

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.

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

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.

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> 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM