window.onunload is not working properly in Chrome browser. Can any one help me?
Solution 1:
There are some actions which are not working in chrome, inside of the unload event. Alert or confirm boxes are such things.
But what is possible (AFAIK):
- Open popups (with window.open) - but this will just work, if the popup blocker is disabled for your site
- Return a simple string (in beforeunload event), which triggers a confirm box, which asks the user if s/he want to leave the page.
Example for #2:
$(window).on('beforeunload', function() {
return 'Your own message goes here...';
});
Demo: http://jsfiddle.net/PQz5k/
Solution 2:
I know this is old but I found the way to make unload work using Chrome
window.onbeforeunload = function () {
myFunction();
};
Solution 3:
Armin's answer is so useful, thank you. #2 is what's most important to know when trying to set up unload events that work in most browsers: you cannot alert() or confirm(), but returning a string will generate a confirm modal.
But I found that even with just returning a string, I had some cross-browser issues specific to Mootools (using version 1.4.5 in this instance). This Mootools-specific implementation worked great in Firefox, but did not result in a confirm popup in Chrome or Safari:
window.addEvent("beforeunload", function() {
return "Are you sure you want to leave this page?";
});
So in order to get my onbeforeonload event to work across browsers, I had to use the JavaScript native call:
window.onbeforeunload = function() {
return "Are you sure you want to leave this page?";
}
Not sure why this is the case, or if it's been fixed in later versions of Mootools.
Solution 4:
You may try to use pagehide event for Chrome and Safari
.
Check these links:
How to detect browser support for pageShow and pageHide?
http://www.webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/