40

Is there an alternative method to use instead of onbeforeunload in mobile-safari? I've noticed that Google was able to capture the onbeforeunload event in mobile-safari. Has anyone figured out how they are doing so?

Google was able to do so using their gmail client. Create a new message... type something in the text area... hit the browser back button. It pops up a warning message. I used an iPad to do my test.

pimvdb
  • 151,816
  • 78
  • 307
  • 352
RJ Herbert
  • 401
  • 1
  • 4
  • 5
  • there is both onunload and onbeforeunload Can you clarify what exactly you're trying to accomplish? – Steve Jul 07 '11 at 00:44
  • 12
    Mobile safari doesn't seem to have onbeforeunload. As for how google is simulating it in gmail, they seem to use an onunload confirm trick with iframes.. See danny armstrong's answer here: http://stackoverflow.com/questions/3239834/window-onbeforeunload-not-working-on-the-ipad I think the page may actually unload when you hit the back button, and the previous gmail page seamlessly picks up from there. Try copying a reply-to URL in gmail, go to an unrelated domain, go to the copied URL, type something in the message, and then try to go back.. the confirm doesn't launch! – Alkanshel Aug 03 '11 at 21:38
  • 1
    See also [window.onbeforeunload not working on the iPad?](http://stackoverflow.com/questions/3239834/window-onbeforeunload-not-working-on-the-ipad) – Peter V. Mørch Aug 07 '13 at 12:26
  • 1
    Perhaps not what you're looking for, but FYI, I have a suggestion for how to [reliably detect `beforeunload` support](http://stackoverflow.com/a/18137334/345716) – Peter V. Mørch Aug 08 '13 at 22:46

2 Answers2

5

I would guess that they are using the History API. By listening to popstate

window.addEventListener("popstate", function(e) { ... });

you can show a warning before allowing doing anything stupid.

rrostt
  • 172
  • 1
  • 6
  • 1
    Hi - this doens't seem to work : window.addEventListener("popstate", function(e) { alert("hi")}); does nothign on an ipad. I see this answer is 5 years ago (!) though ! – user2808054 Apr 14 '16 at 14:20
1

Use pagehide event (reference)

artkoenig
  • 7,117
  • 2
  • 40
  • 61
  • pagehide doens't allow you to add a confirmation popup which was what the orignal quesiton was about (sorry!) – user2808054 Apr 14 '16 at 14:11
  • Read the question before you downvote: "Is there an alternative method to use instead of onbeforeunload in mobile-safari?". the dialog was just an example to test it. – artkoenig Apr 14 '16 at 15:06