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:
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:
tabid
tabs
containing a object those key tabid
is set to 1.tabs
is updated to an object containing tabid
set to 0. tabid
exists, and so does the local storage tabs
key with a sub-key of tabid
the local storage is not cleared.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.tabid
is generated in session storage, but since at least one tabs
[tabid
] exists, the local storage is not cleared