Is there any way to use window.onbeforeunload on Mobile Safari for iOS devices?

允我心安 提交于 2019-11-26 08:14:23

问题


Looks like Apple has disabled the window.onbeforeunload event for iOS devices (iPhone, iPad, iPod Touch). Unfortunately I can\'t find any documentation as to why this event doesn\'t work in Mobile Safari.

Does anyone know if there\'s a reliable alternative to this function? Android\'s browser appears to support it just fine, and the Safari desktop application also supports the onbeforeunload event without issue.


回答1:


I see that it's an old question, but i faced this problem recently.

I'm using window.unload and it works fine in ios browsers (although if you look at Apple documentation it seems to be deprecated and they recommend to use document.pagehide)




回答2:


If you really need it, you cant just get all links, forms and DOM objects that have a handler changing the url and make those wait until you've done what you want. For the links, you get them by getElementsByTagName, check if the href starts with anything but a # and just add your onbeforeunload function add onclick (which will be invoked before the href is looked at). Same for the forms but with onsubmit. And finaly, for the elements changing the href with JavaScript, you should make sure when you add the lsitener that you call your onbeforeunlaod function (or, if you use DOM0 or DOM1 listeners, you can just add some class and then use a global script that checks all elements with the class and adds it to the event listener with a closure.

But you should normaly be able to avoid the use of this event (probably using cookies to store the thing you wanted to send every x seconds and allowing to, in the worst case, have a look at it next time the user loads a page and, in the best case, be able to send an Ajax request at onbeforeunload or onunload which, even if it sends only the http headers, woudl allow you to get what you want).



来源:https://stackoverflow.com/questions/4127621/is-there-any-way-to-use-window-onbeforeunload-on-mobile-safari-for-ios-devices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!