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]

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.


Solution 1:

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.

Solution 2:

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.