Is there an alternative method to use onbeforeunload in mobile safari?
Asked Answered
J

2

41

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.

Janettjanetta answered 1/6, 2011 at 18:32 Comment(4)
there is both onunload and onbeforeunload Can you clarify what exactly you're trying to accomplish?Sisneros
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: #3240334 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!Collie
See also window.onbeforeunload not working on the iPad?Orangeism
Perhaps not what you're looking for, but FYI, I have a suggestion for how to reliably detect beforeunload supportOrangeism
D
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.

Disclosure answered 7/9, 2011 at 21:22 Comment(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 !Hootchykootchy
L
1

Use pagehide event (reference)

Longspur answered 17/1, 2015 at 10:30 Comment(2)
pagehide doens't allow you to add a confirmation popup which was what the orignal quesiton was about (sorry!)Hootchykootchy
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.Longspur

© 2022 - 2024 — McMap. All rights reserved.