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
- 14,494
- 35
- 148
- 243

Praveen Prasad
- 31,561
- 18
- 73
- 106
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
- 479,566
- 201
- 878
- 984
-
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
- 237,923
- 42
- 401
- 438
-
`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
- 321,842
- 108
- 597
- 820
-
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