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.
Asked
Active
Viewed 4.9k times
4 Answers
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;
}
};
Kiquenet
- 13,820
- 33
- 141
- 236
Praveen Prasad
- 30,761
- 16
- 70
- 105
6
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.
alex
- 460,746
- 196
- 858
- 974
-
1Is the same for Alt-F4, and close the navigator (tab or X ) and too F5 key, postback and reload ? – Kiquenet Jul 08 '15 at 10:33
5
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>
jmj
- 232,312
- 42
- 391
- 431
-
`beforeunload` event is meant to return a `string`. [Docs](https://developer.mozilla.org/en/DOM/window.onbeforeunload). – alex Jul 08 '11 at 09:49
-
1
Attach a handler to the unload event.
Aaron Digulla
- 310,263
- 103
- 579
- 794
-
I tried with onbeforeunload event. But the issue is when I refresh the page or do any form submission, it also call the onbeforeunload event. – Lan Jul 08 '11 at 09:33
-
There is no way to distinguish between those; the browser can only tell you that the current document is about to be replaced. That doesn't give you an idea *why* – Aaron Digulla Jul 08 '11 at 15:00