简体   繁体   中英

window event beforeunload was not triggered

I have a piece of code which is storing a boolean flag in the local storage to indicate if there is an instance of the web application open in a browser's tab already.

I'm relying on the beforeunload event to make sure I clear the local storage flag when the user closes the tab.

Sudo code:

if (!isOneTabOpen) {
    localStorage.setItem(isOpenTabKey, 'true');

    window.addEventListener(
      'beforeunload',
      () => {
        localStorage.removeItem(isOpenTabKey);
      },
      false,
    );
  } else {
    window.alert(
      'One more page is open',
    );
    window.location.replace('about:blank');
  }

On of the users of my website complained that they cannot open the website anymore and they see the alert saying 'One more page is open' even thought they don't have the website open.

I tried different ways to make Chrome crash, but I've never managed to get in a state where the localStorage keeps the isOpenTabKey set.

Are there any known cases where the beforeunload event won't fire and thus my local storage is left in a corrupt state, potentially causing this issue?

I think onbeforeunload specification changed silently in recent time. lets check basic example which should work.

window.onbeforeunload = function(e) {
  alert('test');
  console.log('test')
  e.returnValue = 'test';
  return 'test';
};

This simple piece of code handling onbeforeunload event. How it behaves in newest chrome for example.

  • it show browser default message for leaving site with confirmation box with buttons leave and cancel
  • console.log is executed
  • alerts, prompts and other stuff that is blocking javascript execution is automatically blocked.
  • also i have observed, if we open a page with above code and will not do any interaction with page closing tab will be possible without any message, situation change when we do anything like click in the blank spot, in such case default confirmation box will appear and console log will be displayed.

i think your problem may be caused by event listener not attached always. It is currently attached conditionally, lets make if statement inside beforeunload function and do proper checking inside.

window.addEventListener(
  'beforeunload',
  () => {
     if (!isOneTabOpen) {
         // do loacal store stuff
     }
  },
  false,
);

It will make sure your handler is always attached and you can do more debugging if some parts are executed or not, alerts are blocked by chrome so they are not good way to make beforeunload debugging.

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