Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.onbeforeunload not working on the iPad?

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

like image 634
Art Zambrano Avatar asked Jul 13 '10 17:07

Art Zambrano


People also ask

Does Onbeforeunload work on mobile?

Android's browser appears to support it just fine, and the Safari desktop application also supports the onbeforeunload event without issue. This is a duplicate of window. onbeforeunload not working on the iPad? Does this answer your question?

What triggers Onbeforeunload?

The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.


1 Answers

This bit of JavaScript works for me on Safari and Chrome on ipad and iphone, as well as desktop/laptop/other browsers:

var isOnIOS = navigator.userAgent.match(/iPad/i)|| navigator.userAgent.match(/iPhone/i); var eventName = isOnIOS ? "pagehide" : "beforeunload";  window.addEventListener(eventName, function (event) {      window.event.cancelBubble = true; // Don't know if this works on iOS but it might!     ... } ); 
like image 63
Danger Avatar answered Sep 21 '22 12:09

Danger