两个页面之间的sessionStorage

sessionStorage between two pages

我想在一个页面上设置一个变量,然后在另一个页面上显示它。这两个页面都存在于同一个域中。我以前从未使用过 sessionStorage,所以我不确定我在哪里犯了错误。由于某种原因,第二页只是一个空白页。这是第一页上设置变量的代码。

if (typeof(Storage) != "undefined") {
    // Store
    sessionStorage.setItem("score", 12);
    document.getElementById("result").innerHTML = ("score");
} else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}   

这是第二页上的代码,它应该检索变量并将其打印到屏幕上。

if (typeof(Storage) != "undefined") {
    // Retrieve
    document.getElementById("result").innerHTML = sessionStorage.getItem("score");
} else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}

任何关于为什么这没有得到变量的见解都将非常感谢。

"...sessionStorage gets cleared when the page session ends"

改用localStorage

sessionStorage 描述:

  • 页面会话结束时清除
  • 在新选项卡中打开页面或 window 将启动新会话

改为使用 localStorage

正如 Yiriy 所指出的,当尝试在多个 windows/tabs 浏览器之间共享一个变量时,应该使用 localStorage 而不是 sessionStorage。

所以使用:

localStorage.setItem("score",12);

document.getElementById("result").innerHTML = localStorage.getItem("score");

在另一个选项卡中

想想sessionStorage存储局部变量而localStorage存储全局变量

When a user opens a new tab, we first ask any other tab that is opened if he already have the sessionStorage for us. If any other tab is opened it’ll send us the sessionStorage through localStorage event, we’ll duplicate that into the sessionStorage.

// on opening the new tab, we check the session storage. 
// if it's empty, we send (from the new tab) an localStorage event, with particular key(getSessionStorage), by setting some value in localStorage
if (!sessionStorage.length) {
  localStorage.setItem('getSessionStorage', Date.now()); // send Event1 from new tab
};

window.addEventListener('storage', function(event) {
  // in first tab, we listen for the "getSessionStorage" event and set the sessionStorage info in the localStorage.
  if (event.key == 'getSessionStorage') { // Event1 captured in first tab
    localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage)); // emit Event2 from first tab. this contains session storage info.
    localStorage.removeItem('sessionStorage');
  } else if (event.key == 'sessionStorage' && !sessionStorage.length) { // capture Event2 in new tab. read the event value and set in session storage in new tab
    var data = JSON.parse(event.newValue);
    for (key in data) {
      sessionStorage.setItem(key, data[key]);
    }
  }
});

来源 - https://blog.guya.net/2015/06/12/sharing-sessionstorage-between-tabs-for-secure-multi-tab-authentication/