After looking at this question 6 years after it was asked, I found that there still is no sufficient answer to this question; which should achieve all of the following:
- Clear Local Storage after closing the browser (or all tabs of the domain)
- Preserve Local Storage across tabs, if at least one tab remains active
- Preserve Local Storage when reloading a single tab
Execute this piece of javascript at the start of each page load in order to achieve the above:
((nm,tm) => { const l = localStorage, s = sessionStorage, tabid = s.getItem(tm) || (newid => s.setItem(tm, newid) || newid)((Math.random() * 1e8).toFixed()), update = set => { let cur = JSON.parse(l.getItem(nm) || '{}'); if (set && typeof cur[tabid] == 'undefined' && !Object.values(cur).reduce((a, b) => a + b, 0)) { l.clear(); cur = {}; } cur[tabid] = set; l.setItem(nm, JSON.stringify(cur)); }; update(1); window.onbeforeunload = () => update(0); })('tabs','tabid');
Edit: The basic idea here is the following:
- When starting from scratch, the session storage is assigned a random id in a key called
tabid - The local storage is then set with a key called
tabs containing a object those key tabid is set to 1. - When the tab is unloaded, the local storage's
tabs is updated to an object containing tabid set to 0. - If the tab is reloaded, it's first unloaded, and resumed. Since the session storage's key
tabid exists, and so does the local storage tabs key with a sub-key of tabid the local storage is not cleared. - When the browser is unloaded, all session storage will be cleared. When resuming the session storage
tabid won't exists anymore and a new tabid will be generated. Since the local storage does not have a sub-key for this tabid, nor any other tabid (all session were closed), it's cleared. - Upon a new created tab, a new
tabid is generated in session storage, but since at least one tabs[tabid] exists, the local storage is not cleared
undefinedwould overwrite the previously stored item though. But yes, using.removeItem()is more appropriate.localStorage.clear();if you want to clear whole storage.