window.onunload is not working properly in Chrome browser. Can any one help me?

Imran picture Imran · Oct 17, 2011 · Viewed 135.7k times · Source

I have written this code

function winUnload() {
    alert("Unload Window");
    MyMethod();
}

window.onunload = function() { winUnload(); }

This code is working fine in IE and Firefox. But this code is not working in Chrome. Both the statements alert("Unload Window"); and MyMethod(); are not working.

Answer

Armin picture Armin · Feb 17, 2012

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):

  1. Open popups (with window.open) - but this will just work, if the popup blocker is disabled for your site
  2. 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/