我在我的网站上有一些值,我想在浏览器关闭时清除。我选择sessionStorage来存储这些值。当tab被关闭时,它们确实被清除,如果用户按f5则保留;但是如果用户在不同的标签中打开一些链接,这些值是不可用的。

我如何与我的应用程序共享所有浏览器选项卡之间的sessionStorage值?

用例:将一个值放在某个存储空间中,使该值在所有浏览器选项卡中都可访问,并在所有选项卡关闭时将其清除。

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

当前回答

为此使用sessionStorage是不可能的。

来自MDN文档

在一个新的选项卡或窗口中打开一个页面将导致一个新的会话 启动。

这意味着你不能在标签间共享,为此你应该使用localStorage

其他回答

我发现在选项卡之间共享sessionStorage的唯一方法是window.open:

Window.open ('./page2.html', ")用一个新标签打开page2 window.open('./page2.html','height=100, width=100')在新窗口中用新标签打开page2。

Page2可以从page1获得一个sessionStorage对象的副本,但是这两个sessionStorage对象是相互独立的。

为此使用sessionStorage是不可能的。

来自MDN文档

在一个新的选项卡或窗口中打开一个页面将导致一个新的会话 启动。

这意味着你不能在标签间共享,为此你应该使用localStorage

如果您有少量的数据,您可以使用会话cookie来代替sessionStorage,该会话cookie在用户关闭浏览器或清除cookie之前一直处于活动状态。它还在多个制表符之间保存其值。

设置cookie的代码

document.cookie = "cookiename=value; path=/";

通过省略expires,我们设置了一个会话cookie。

然后像这样检索它:

function getCookie(name) {
  var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
  if (match) return match[2];
}

var value = getCookie('cookiename');

You can just use localStorage and remember the date it was first created in session cookie. When localStorage "session" is older than the value of cookie then you may clear the localStorage Cons of this is that someone can still read the data after the browser is closed so it's not a good solution if your data is private and confidental. You can store your data to localStorage for a couple of seconds and add event listener for a storage event. This way you will know when any of the tabs wrote something to the localStorage and you can copy its content to the sessionStorage, then just clear the localStorage

实际上看看其他区域,如果你用_blank打开,它会保留sessionStorage,只要你在打开父选项卡时打开:

在这个链接中,有一个很好的jsfiddle来测试它。 当跟随target="_blank"的链接时,新窗口上的sessionStorage不是空的