I'm adding a "confirm that you want to leave" dialogue to my website and am experiencing a strange behaviour of the onbeforeunload event.
The docs are pretty clear: If your page is about to be unloaded, this event is called. When your eventHandler returns a string, the user is asked for confirmation. Depending on the browser, the string may be displayed to him.
But in a small sample website, I noticed that beforeunload is only actually fired if the user somehow interacted with the website. This is my test setup:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script type="text/javascript"> window.onload = function () { $("#placeholder").text("website loaded") window.onbeforeunload = function () { return "Reloading the page will reset the survey!"; } } </script> </head> <body> <p id='placeholder'></p> </body> </html> When the window is loaded, the paragraph text is changed and an eventHandler for beforeunload is registered. If I load this in Firefox, the paragraph is immediately changed.
But if I close the tab or reload it, no confirmation is asked. The confirmation dialogue is only displayed if I have clicked in the website. Switching tabs back and forth is not enough, waiting for ca 10s is not enough.
The behaviour is the same in chrome.
Once I have clicked in the website, the confirmation is always asked. I can have another tab focused and close this example (by right-click and "close tab"), it asks for confirmation. Or another tab is focused and I try to close the browser, it asks for confirmation.
What is happening here, how can I make sure that the event is always fired before the site is unloaded ?
