Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save KRostyslav/539dabb4285c49bc3eb269dfc30f8452 to your computer and use it in GitHub Desktop.
Save KRostyslav/539dabb4285c49bc3eb269dfc30f8452 to your computer and use it in GitHub Desktop.
Clear localStorage on close tabs/browser
((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