0
votes

I have an application which stores the user data in browser's localStorage. So, user can get those data even across browser tabs and windows. But what I want to do is to clear localStorage when user closes the browser window.

I used beforeunload function to achieve this but it triggers on tab close also.

So, please help me if there is any way to detect whether browser tab is closed or browser window.

PS: I can't use sessionStorage as it destroys on browser tab close.

1
AFAIK not without games; searching the web and SO will provide multiple ideas you can explore. - Dave Newton

1 Answers

1
votes

Use Session Storage in the browser.
Here you don't want to capture the browser tab closing event. The Session Storage data persist for a session of opened tab

if (sessionStorage.clickcount) {
    sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
    sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";

I grab those example code from Here

Only Clear when Browser close

localStorage.removeItem(key);

Hope this will help you