window.onbeforeunload not working on the iPad?

Art Zambrano picture Art Zambrano · Jul 13, 2010 · Viewed 49.1k times · Source

Does anyone know if the onbeforeunload event is supported on the iPad and/or if there's a different way to use it?

I've tried pretty much everything, and it seems like the onbeforeunload event is never triggered on the iPad (Safari browser).

Specifically, this is what I've tried:

  • window.onbeforeunload = function(event) { event.returnValue = 'test'; }
  • window.onbeforeunload = function(event) { return 'test'; }
  • (both of the above together)
  • window.onbeforeunload = function(event) { alert('test')'; }
  • (all of the above functions but inside <body onbeforeunload="...">

All of these work on FF and Safari on the PC, but not on the iPad.

Also, I've done the following just after loading the page:

alert('onbeforeunload' in window);
alert(typeof window.onbeforeunload);
alert(window.onbeforeunload);

Respectively, the results are:

  • true
  • object
  • null

So, the browser does have the property, but for some reason it doesn't get fired.

The ways I try to navigate away from the page are by clicking the back and forward buttons, by doing a google search in the top bar, by changing location in the address bar, and by clicking on a bookmark.

Does anyone have any idea about what's going on? I'd greatly appreciate any input.

Thanks

Answer

Danny Armstrong picture Danny Armstrong · Jan 28, 2011

I have found that the onunload() event does fire. It's behavior is somewhat odd; whatever you have in your callback function attached to the event is actually run after the new page has loaded in the background (You can't tell it's loaded yet, but server logging will show that it has).

More oddly, if you have a confirm() call in your onunload(), and the user has clicked a link to go somewhere else, you are in business. If, however, the user closes the iPad Safari browser tab, the onunload() event will fire, but your confirm() will have an implicit cancel as response.