win8.1中的localStorage IE11不同步

dev*_*per 11 javascript html5 internet-explorer local-storage internet-explorer-11

我们有两页"/ read"和"/ write".页面"/ write"每秒用当前时间更新localStorage:

setInterval(function(){
    var time = (new Date()).getTime();
    localStorage.setItem("time", time);
    console.log("set", time);
},1000);
Run Code Online (Sandbox Code Playgroud)

页面"/ read"读取相同的存储空间:

setInterval(function(){
    var time = localStorage.getItem("time");
    console.log("get", time);
},1000);
Run Code Online (Sandbox Code Playgroud)

有人会认为"/ read"页面应该显示由另一个页面写入localStorage的相同值.但是在Win8.1的IE11中,这已经破了.页面"/ read"从存储中读取一些旧值,并在其上显示相同的值(就像它使用缓存进行本地存储一样).有任何想法吗?

PS这两个网页位于同一个域(活生生的例子- )

小智 7

我在Win 10上找到了解决此问题的方法.如果您在代码中处理window.onstorage事件,则localStorage将刷新所有打开的选项卡.这件事对我来说很简单:

window.onstorage = function(e){
    //Leave this empty
    //or add code to handle
    //the event
};
Run Code Online (Sandbox Code Playgroud)

我没有彻底测试过这段代码,所以请在任何生产应用程序中使用此方法之前执行此操作.

希望这可以帮助!


Kev*_*evD 6

看来IE11 / Windows 8下的localStorage.GetItem方法不可靠,并且可能会检索以前的值。但这可以通过在检索值之前立即调用localStorage.SetItem方法来解决。

我设法使用muttonUp的代码复制了此问题,然后进行了以下更改以使两个窗口相互通信:

<!DOCTYPE html>
<head>
    <title>LocalStorage Test</title>
</head>
<body>
<button onclick="setLocalStorageValue()">Set Time</button>

<script>
    setInterval(function () {
        window.localStorage.setItem("unused_key",null);
        console.log(window.localStorage.getItem("test_key"));
    }, 1000);

    function setLocalStorageValue () {
        console.log("Button clicked - setting time");
        window.localStorage.setItem("test_key", new Date().getTime());
    }
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

这是输出: 两个IE11浏览器实例共享localStorage

在我的情况下,此解决方法非常有用,因为我仅以不频繁的时间间隔从localStorage检索值,并且仅存储少量数据。由于setItem方法调用数量的增加可能会带来性能开销,因此在使用这种变通方法时,往返于localStorage的流量会比较大,因此我可能会仔细考虑。


mut*_*nUp 5

与其说是答案,不如说是进一步调查。使用以下页面,可以通过托管在 Web 服务器上并在不同选项卡中打开它来轻松测试此问题。然后单击其中一个选项卡中的按钮。

<!DOCTYPE html>
<head>
    <title>LocalStorage Test</title>
</head>
<body>
<button onclick="setLocalStorageValue()">Set Time</button>

<script>
    setInterval(function () {
        console.log(window.localStorage.getItem("test_key"));
    }, 1000);

    function setLocalStorageValue () {
        window.localStorage.setItem("test_key", new Date().getTime());
    }
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

无论操作系统如何,Chrome/Firefox/Safari 中的结果都是相同的。它们表明 localStorage 在来自同一 Origin 的页面之间共享。

在 Windows 7 上的 IE11 上,也给出了相同的结果。 在此处输入图片说明

根据我所阅读的内容,这似乎符合规范,此处为第 3 点https://html.spec.whatwg.org/multipage/webstorage.html#the-localstorage-attribute

但...

  • Windows 8.1 上的 IE 11 将演示相同来源的单独 localStorage 区域。 在此处输入图片说明

  • Windows 10 (10162) 上的 Microsoft Edge 也有同样的问题。 在此处输入图片说明 IE11 在 Windows 7 上显示“正确”行为的事实表明操作系统是问题所在?