I have some values in my site which I want to clear when the browser is closed. I chose sessionStorage to store those values. When tab is closed they are indeed cleared, and kept if the user presses f5; But if the user opens some link in a different tab these values are unavailable.

How I can share sessionStorage values between all browser tabs with my application?

The use case: put a value in some storage, keep that value accessible in all browser tabs and clear it if all tabs are closed.

if (!sessionStorage.getItem(key)) {
    sessionStorage.setItem(key, defaultValue)
}

推荐答案

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 another
var 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 localStorage
if(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/

Javascript相关问答推荐

reaction useEffect KeyDown for each 条目配音输出

我的glb文件没有加载到我的three.js文件中

如何才能拥有在jQuery终端中执行命令的链接?

从mat—country—select获取整个Country数组

使搜索栏更改语言

处理时间和字符串时MySQL表中显示的日期无效

Html文件和客户端存储的相关问题,有没有可能?

变量的值在Reaction组件中的Try-Catch语句之外丢失

使用Java脚本导入gltf场景并创建边界框

当id匹配时对属性值求和并使用JavaScript返回结果

将数组扩展到对象中

如何防止ionic 输入中的特殊字符.?

expo 联系人:如果联系人的状态被拒绝,则请求访问联系人的权限

警告框不显示包含HTML输入字段的总和

当从其他文件创建类实例时,为什么工作线程不工作?

将相关数据组合到两个不同的数组中

判断函数参数的类型

Next.js无法从外部本地主机获取图像

如何在不将整个文件加载到内存的情况下,在Node.js中实现Unix粘贴命令?

在Reaction Native中,ScrolltoIndex在结束时不一致地返回到索引0