-1

Is it possible to delete localStorage data/logout after closing tab/browser window but not for refreshing that page of the project. So cause if some closes it, user have to login again. Thanks

  • 7
    Try [`sessionStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) instead. – 31piy Jun 08 '18 at 11:43
  • 1
    Or look into https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload –  Jun 08 '18 at 11:43
  • "window.onbeforeunload" working but also in refresh the page. page may be refresh again again but should not be remove my storage Data for the refresh page. function should only call while close the tab/windows. – Bishnu Kumar Bhakat Jun 08 '18 at 11:47

2 Answers2

0

This should work:

localStorage.setItem("someVar","someValue");
window.onbeforeunload = function(){
  localStorage.removeItem("someVar");
};

But it's better sessionStorage

 sessionStorage.setItem("someVar","someValue");

When user leaves the page all items are removed

Emeeus
  • 5,072
  • 2
  • 25
  • 37
  • yes ! I did this but this is happening for also refreshing that page. – Bishnu Kumar Bhakat Jun 08 '18 at 11:54
  • So, you should .setItem when document load and remove it when onbeforeunload, because there is no tab close event https://stackoverflow.com/questions/3888902/detect-browser-or-tab-closing – Emeeus Jun 08 '18 at 12:18
0

If you want to delete anything on close of tab use sessionStorage rather than localStorage as:

sessionStorage.setItem("key","value");
Anshuman Jaiswal
  • 5,352
  • 1
  • 29
  • 46