Last active
June 16, 2020 10:04
-
-
Save KRostyslav/539dabb4285c49bc3eb269dfc30f8452 to your computer and use it in GitHub Desktop.
Clear localStorage on close tabs/browser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
((nm, tm) => { | |
const lStorage = localStorage; | |
const sStorage = sessionStorage; | |
const tabId = sStorage.getItem(tm) | |
|| ((newId) => { | |
sStorage.setItem(tm, newId); | |
return newId; | |
})((Math.random() * 1e8).toFixed()); | |
const update = (setTabValue) => { | |
let currentValue = JSON.parse(lStorage.getItem(nm) || '{}'); | |
const arrValue: number[] = Object.values(currentValue); | |
if (setTabValue | |
&& typeof currentValue[tabId] === 'undefined' | |
&& !arrValue.reduce((sum, current) => { return sum + current; }, 0)) { | |
lStorage.clear(); | |
currentValue = {}; | |
} | |
currentValue[tabId] = setTabValue; | |
lStorage.setItem(nm, JSON.stringify(currentValue)); | |
}; | |
update(1); | |
window.onbeforeunload = () => { update(0); }; | |
})('tabs', 'tabid'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment