By binding onbeforeunload
to window
like this window.onbeforeunload
it should trigger in most browsers. check this fiddle. It seems it's not supported on IOS devices.
For IOS apple docs suggest using pagehide
see apple page on Handling Events.
The load and unload events may not work as expected for back and forward optimization. Use the pageshow and pagehide events instead.
Keep in mind that this will also trigger on all other kinds of navigation away from the page. Such as close, tab close, back/ forward navigation, link navigation and address bar navigation
Checking if the browser is reloading versus navigating away from the page I'm pretty confident is not possible, due to security/ privacy reasons not being able to give you the destination url. You could eliminate link presses by using it is an condition when firing the onbeforeunload
.
Edit: If you need to check if the page has been reloaded however, you could use sessionvariables or cookies to store that the user has already opened the page once before.