browser sessionStorage. share between tabs? browser sessionStorage. share between tabs? javascript javascript

browser sessionStorage. share between tabs?


You can use localStorage and its "storage" eventListener to transfer sessionStorage data from one tab to another.

This code would need to exist on ALL tabs. It should execute before your other scripts.

// transfers sessionStorage from one tab to anothervar sessionStorage_transfer = function(event) {  if(!event) { event = window.event; } // ie suq  if(!event.newValue) return;          // do nothing if no value to work with  if (event.key == 'getSessionStorage') {    // another tab asked for the sessionStorage -> send it    localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage));    // the other tab should now have it, so we're done with it.    localStorage.removeItem('sessionStorage'); // <- could do short timeout as well.  } else if (event.key == 'sessionStorage' && !sessionStorage.length) {    // another tab sent data <- get it    var data = JSON.parse(event.newValue);    for (var key in data) {      sessionStorage.setItem(key, data[key]);    }  }};// listen for changes to localStorageif(window.addEventListener) {  window.addEventListener("storage", sessionStorage_transfer, false);} else {  window.attachEvent("onstorage", sessionStorage_transfer);};// Ask other tabs for session storage (this is ONLY to trigger event)if (!sessionStorage.length) {  localStorage.setItem('getSessionStorage', 'foobar');  localStorage.removeItem('getSessionStorage', 'foobar');};

I tested this in chrome, ff, safari, ie 11, ie 10, ie9

This method "should work in IE8" but i could not test it as my IE was crashing every time i opened a tab.... any tab... on any website. (good ol IE) PS: you'll obviously need to include a JSON shim if you want IE8 support as well. :)

Credit goes to this full article:http://blog.guya.net/2015/06/12/sharing-sessionstorage-between-tabs-for-secure-multi-tab-authentication/


Using sessionStorage for this is not possible.

From the MDN Docs

Opening a page in a new tab or window will cause a new session to be initiated.

That means that you can't share between tabs, for this you should use localStorage


Actually looking at other areas, if you open with _blank it keeps the sessionStorage as long as you're opening the tab when the parent is open:

In this link, there's a good jsfiddle to test it.sessionStorage on new window isn't empty, when following a link with target="_blank"