简体   繁体   中英

Best way to detect browser window changes like go back, url change, reload, close event

So I am working on a testing application and I need to call a finsihTheTest() function (ie this function finishes the test by saving answers, time and other information) whenever following conditions occur:

  1. User tries to reload page.
  2. User tries to go back from the page.
  3. User tries to close the tab.
  4. User tries to close the browser window.
  5. User goes to another url.
  6. If anything happens that closes the page like laptop/PC shutdown, inte.net lost or anything else.

What I exactly want to do is, if once a user starts the test and by any mean he attempts to leave I want to save his state. Which is being done by the function finishTheTest() .

I got a clue but it didn't work:

function UnLoadWindow() {
    return 'We strongly recommends NOT closing this window yet.'
}

window.onbeforeunload = UnLoadWindow;

To get the full results for your cases there's many things you should now on how browsers react on many scenarios.

To understand more please read this section :

Especially on mobile, the unload event is not reliably fired. For example, the unload event is not fired at all in the following scenario:

A mobile user visits your page.

The user then switches to a different app.

Later, the user closes the browser from the app manager.

Also, the unload event is not compatible with the back/forward cache (bfcache), because many pages using this event assume that the page will not continue to exist after the event is fired. To combat this, some browsers (such as Firefox) will not place pages in the bfcache if they have unload listeners , and this is bad for performance. Others, such as Chrome, will not fire the unload when a user navigates away.

If you're specifically trying to detect page unload events , it's best to listen for the pagehide event.

 window.addEventListener('pagehide', function(event) { document.cookie = "saveData=test" },false)

This way you can save your user current data and reload it on next page window load event

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM