I want to clear my local storage after closing the browser, for that I control all active tabs using sessionStorage
so, my App.js looks like this:
window.onload = () => {
var tabID = sessionStorage.getItem("tab_id");
if (tabID === null) {
var hash = Math.random(10**5).toString(36)
sessionStorage.setItem("tab_id", hash);
var allTabs = localStorage.getItem("all_tabs");
if (allTabs ==null || allTabs==''){
console.log(1)
allTabs=[]
}
else{
console.log(1, allTabs)
allTabs = allTabs.split(',');
}
console.log(allTabs)
allTabs.push(hash)
console.log(hash, 'local', allTabs)
localStorage.setItem("all_tabs", allTabs);
}
}
window.onunload = () => {
var tabID = sessionStorage.getItem("tab_id");
var allTabs = localStorage.getItem("all_tabs");
var locItemsArr = allTabs.split(',');
var ind = locItemsArr.indexOf(tabID)
locItemsArr.splice(ind,1)
localStorage.setItem("all_tabs", locItemsArr.toString());
if (localStorage.getItem("all_tabs") == "" ) {
console.log('clear')
localStorage.clear()
}
}
However, I didn't took into account the fact that onunload will also be triggered when the page is updated. Is there any way to understand if the page is closing or just being updated to clear localStorage only after closing?