3

Need to clear local storage on browser tab closed not on refresh. I tried

window.onbeforeunload = function (e) {
    localStorage.clear();
};

it clears the localstorage when browser refresh happens. I want to force the user to login when the user close browser tab.

phuzi
  • 12,078
  • 3
  • 26
  • 50
Sankar
  • 343
  • 2
  • 6
  • 18
  • 1
    Possible duplicate of https://stackoverflow.com/questions/9943220/how-to-delete-a-localstorage-item-when-the-browser-window-tab-is-closed – Karan Dhir Oct 16 '17 at 12:39
  • Try this `localStorage.$reset();` – Ramesh Rajendran Oct 16 '17 at 12:45
  • 1
    Possible duplicate of [How to delete a localStorage item when the browser window/tab is closed?](https://stackoverflow.com/questions/9943220/how-to-delete-a-localstorage-item-when-the-browser-window-tab-is-closed) – Ramesh Rajendran Oct 16 '17 at 12:45

2 Answers2

4

Refreshing and closing a tab/window is the same event as far as the browsers are concerned.

Best would be to use session storage rather than local storage as session would be active until the tab/window is closed and not refreshed and you aren't saving persistent data.

Have a look here

Abdul Sadik Yalcin
  • 1,744
  • 2
  • 19
  • 50
-3

Use this code.

window.onload = window.localStorage.clear();
4b0
  • 21,981
  • 30
  • 95
  • 142