Skip to content

Instantly share code, notes, and snippets.

@afrozek
Last active January 18, 2022 03:18
Show Gist options
  • Save afrozek/6ff028acee797a194adbd2d371644046 to your computer and use it in GitHub Desktop.
Save afrozek/6ff028acee797a194adbd2d371644046 to your computer and use it in GitHub Desktop.
Maintain Session Storage Across Tabs. NOT created by me all credit to: http://blog.guya.net/2015/06/12/sharing-sessionstorage-between-tabs-for-secure-multi-tab-authentication/
(function() {
//source: http://blog.guya.net/2015/06/12/sharing-sessionstorage-between-tabs-for-secure-multi-tab-authentication/
if (!sessionStorage.length) {
// Ask other tabs for session storage
localStorage.setItem('getSessionStorage', Date.now());
};
window.addEventListener('storage', function(event) {
//console.log('storage event', event);
if (event.key == 'getSessionStorage') {
// Some tab asked for the sessionStorage -> send it
localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage));
localStorage.removeItem('sessionStorage');
} else if (event.key == 'sessionStorage' && !sessionStorage.length) {
// sessionStorage is empty -> fill it
var data = JSON.parse(event.newValue),
value;
for (key in data) {
sessionStorage.setItem(key, data[key]);
}
showSessionStorage();
}
});
window.onbeforeunload = function() {
//sessionStorage.clear();
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment