Which event handler to use to record leaving page - onunload or onbeforeunload?

一曲冷凌霜 提交于 2019-12-11 13:02:22

问题


Having not any answers to my previous questions about using javascript to measure page turn times, I'm going to start writing my own code (!).

To measure the length of tie it takes, I'm proposing dropping a cookie containing a timestamp when the user browses away from a page, then in a subsequent page, comparing that time with 'now' and sending back a request to a URL which will log the interval.

It seems that there are 2 possible handlers I could associate the first block of code with - the onunload() handler or the onbeforeunload()?

It's more important that it fail silently on browsers with no/broken support for the handler, than it be portable across every possible browser.

Any pointers? Gotchas?

TIA

C.


回答1:


onbeforeunload is not supported by Opera, and is really meant to be used to give the user a chance to abort the unload, so you should go for onunload.




回答2:


One thing with either onunload or onbeforeunload is that any Ajax call must have async: false property. This prevents the code from actually leaving until the call completes. Other than that, see Sean Kinsey's answer.




回答3:


I'm trying to use onunload in Firefox but it seems like it doesn't give the Javascript much time to do anything useful, so it's a cross browser issue. I might want to use a combination of both handlers.



来源:https://stackoverflow.com/questions/2849034/which-event-handler-to-use-to-record-leaving-page-onunload-or-onbeforeunload

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