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.
A tab or window closing in a browser can be detected by using the beforeunload event. This can be used to alert the user in case some data is unsaved on the page, or the user has mistakenly navigated away from the current page by closing the tab or the browser.
The best way I found to reload the page without losing cookies, and remove cookies on window or tab close was to use ng-keydown to watch the F5 Keypress (KeyCode 116).
JavaScript provides an in-built function named close() to close the browser window that is opened by using window. open() method.
The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.
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;
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With