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!
©2020 All rights reserved.