Is there a way to detect tab close event to clear the localStorage
. I need localStorage
to share data across tabs. window.onbeforeunload
event works fine but it has 2 issues for me:
Like when window is closed the sessionStorage
is cleared. At same time I can clear localStorage
but don't know what event to bind to. I checked a few questions already available but none seems to address this issue there are workarounds by using flags for click on links and form submits but not a clean way to do it. Kindly suggest any solution for this.
I know that that is an old question, but I was just looking for a solution for this, but I couldn't find anything that works properly. Then I came up with a solution which is working fine for me.
What I did was to change the perspective, instead of clearing the local storage when the browser is closed I decided to clear it when it is opened. Users won't see the difference.
I just set a function that check the sessionStorage when the page is loaded, if it is empty the function gets the localStorage cleared; After that it sets a register
to sessionStorage to ensure that the localStorage won't be emptied again just for having the page reloaded.
function clearStorage() {
let session = sessionStorage.getItem('register');
if (session == null) {
localStorage.removeItem('remove');
}
sessionStorage.setItem('register', 1);
}
window.addEventListener('load', clearStorage);
I was able to find solution to this and thought of sharing. Since the window.onbeforeunload event fires on browser/tab close but on refresh as well(which i did not want) the thing was my localstorage was being processed at time of rfresh as well. Which I did not want. In order to overcome this I implemented 1 more event handler window.onload that fires only on refresh and not on tab/browser close where I would reset the localStorage as if nothing had happened. The code is:
window.onbeforeunload = function (e) {
window.onunload = function () {
window.localStorage.isMySessionActive = "false";
}
return undefined;
};
window.onload = function () {
window.localStorage.isMySessionActive = "true";
};
I returned undefined in window.onbeforeunload as i did not want a confirm popup to appear on tab/browser close and refresh.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With