views:

2762

answers:

3

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.

+1  A: 

No, I don't think there is.

Jeff
+4  A: 

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.

some
A: 

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!

Doesn't work at all when **clicking** the close button with the **mouse**.
deceze