Home > Software engineering >  Record if the user clicked 'cancel' on Javascript 'beforeunload' event
Record if the user clicked 'cancel' on Javascript 'beforeunload' event

Time:12-25

I'm trying to perform some actions if the user closes the browser tab. Below is my code.

function myfun(){
  console.log('action performed')
}

window.onbeforeunload = function(e){
  e.preventDefault()
  myfun()
  return 'Are you sure you want to leave?';
};

My code works, but the issue i'm facing is, on the prompt if the user click on the cancel button doesn't close the tab, my function still runs. Is there way to record that the user has clicked on the cancel button ?

I've tried to modify the 'myfun' function as below, but didn't helped.

function myfun(){
  if(window.close()){
    console.log('action perfomed')
  }
}

CodePudding user response:

You can use the unload event. Since most browser delete the log of a page once it's unloaded, I replaced it with a localStorage example.

function myfun(){
  localStorage.setItem('myCat', 'Tom');
}

window.onbeforeunload = function(e){
  e.preventDefault()
  return 'Are you sure you want to leave?';
};

window.onunload = myfun;
if(localStorage.getItem("myCat")!=null)
  alert("Last time this page was closed the unload event was called!");
localStorage.setItem('myCat', null);

Unload event will not always be fired, as Mozilla states :

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

  1. A mobile user visits your page.
  2. The user then switches to a different app.
  3. Later, the user closes the browser from the app manager.

It's better to use visibilitychange event or pagehide event, even though they do not fully replace the unload event.

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.

The best event to use to signal the end of a user's session is the visibilitychange event. In browsers that don't support visibilitychange the next-best alternative is the pagehide event, which is also not fired reliably, but which is bfcache-compatible.

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

CodePudding user response:

I think it's not possible to check whether user pressed cancel button. In other way you can use onunload event as per below code.

window.onunload = function(e) {
      console.log("unload event");
    };

If the user clicks on reload then this will be called.

  • Related