0

so I want my app that when I close the tab is to clear the localStorage, so I tried this:

    window.addEventListener('beforeunload', function (e) {
        e.preventDefault();
        this.localStorage.clear()
        e.returnValue = '';
    });

But the problem is it also runs when I refresh the page so the items on my localStorage gets cleared even on refresh and now I have to re log in again, is there a function that only detects when I close the tab?

user3352042
  • 131
  • 1
  • 3
  • 16
  • Short answer: no not really: [javascript beforeunload detect refresh versus close](https://stackoverflow.com/questions/11453741/javascript-beforeunload-detect-refresh-versus-close) – Zac Anger Nov 25 '22 at 00:51
  • If you use [`sessionStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) then you'll get this exact behavior for free. – Peter B Nov 25 '22 at 00:53

1 Answers1

0

I don't think you can. There is very limited information about what goes on in a browser outside of your app. Many of these functionalities are available through particular APIs instead of being directly exposed.

I suggest using session storage as this is its default behaviour and intended use.

This remind me that you can only know that a 'POP' action was dispatched when a user clicks the back or forward buttons. You cannot know which one of them was pressed though.

fum4
  • 237
  • 2
  • 13