carry forward session storage one page to another page in javascript

Solutions on MaxInterview for carry forward session storage one page to another page in javascript by the best coders in the world

showing results for - "carry forward session storage one page to another page in javascript"
Lotta
20 Feb 2019
1// transfers sessionStorage from one tab to another
2var sessionStorage_transfer = function(event) {
3  if(!event) { event = window.event; } // ie suq
4  if(!event.newValue) return;          // do nothing if no value to work with
5  if (event.key == 'getSessionStorage') {
6    // another tab asked for the sessionStorage -> send it
7    localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage));
8    // the other tab should now have it, so we're done with it.
9    localStorage.removeItem('sessionStorage'); // <- could do short timeout as well.
10  } else if (event.key == 'sessionStorage' && !sessionStorage.length) {
11    // another tab sent data <- get it
12    var data = JSON.parse(event.newValue);
13    for (var key in data) {
14      sessionStorage.setItem(key, data[key]);
15    }
16  }
17};
18
19// listen for changes to localStorage
20if(window.addEventListener) {
21  window.addEventListener("storage", sessionStorage_transfer, false);
22} else {
23  window.attachEvent("onstorage", sessionStorage_transfer);
24};
25
26
27// Ask other tabs for session storage (this is ONLY to trigger event)
28if (!sessionStorage.length) {
29  localStorage.setItem('getSessionStorage', 'foobar');
30  localStorage.removeItem('getSessionStorage', 'foobar');
31};
32