开发者

Is there a way in javascript to detect if the unload event is caused via a refresh, the back button, or closing the browser? [duplicate]

This question already has answers here: Identifying Between Refresh And Close Browser Actions (13 answers) Closed 6 years ago.

I am currently looking at the "unload" event of a window to try to determine how the "unload" event was triggered, but am having little success. Is there a way to determine how the javascript event was triggered?

  • Page Refresh
  • Back Button (or navigate away from the page)
  • Closing the Browser

Essentially I need to execute some code only when the browser window is being closed, not refreshed or navigated away from.

Purpose: When a customer does an update of our software, the update will redirect their first Internet request to an offer开发者_开发问答 page. There is a button for a "Do Not Bother" option, but some users will simply close their browser. Upon closing the browser, I need to duplicate the "Do Not Bother" functionality so the user no longer gets redirected to the offer page. Simply attaching to the "unload" event will not work due to the different ways of leaving a page.


No, and if there was it would be browser dependent. What kind of code are you trying to run when the user closes the page? Is it to logout the user? Then the user would not be logged out if the browser crashes or the network connection breaks (and probably not if the computer goes to sleep/hibernation mode).

If it is for logout-purposes you should probably use a timestamp variable at the server that gets updated with every request (or use a ajax-ping), and logout the user if it hasn't been seen for a specified time.

Update: Found this answer here at stackoverflow.


Yes, there is a solution!

I've designed a solution based on onBeforeUnload+onLoad events, HTML5 local storage and client/server communication. See the details on https://stackoverflow.com/a/13916847/698168.


I use a method of doing keyboard "sniffing", in that it looks for keydown's of "F5", "ctrl+r", "alt-f4", "backspace" and others, and if it finds them flowing through the keyboard event queue, it sets boolean variables appropriately to trap that status... then I use a "onbeforeunload" function handler, which tests against those boolean status variables to decide what to do.

You can even shut down various keyboard strokes (like "ctrl+n" or "F1" for instance) by using preventDefault(), bubbles=false and returnValue=false in your keyboard handling.

This stuff is not for the faint of heart, but its certainly doable with some persistence and lots of cross browser testing!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜