IE localStorage 事件失火

2024-05-23

在 Internet Explorer 9 和 10 中,localStorage 实现意外地触发事件(这里有很棒的线索:Chrome 的 localStorage 实现存在错误? https://stackoverflow.com/questions/4679023/bug-with-chromes-localstorage-implementation)

有谁知道有什么方法可以阻止storage在 Internet Explorer 中启动更改的选项卡上触发的事件?

例如,单击添加按钮时,以下内容不应显示警报,但在 IE 中会显示警报:

fiddle: http://jsfiddle.net/MKFLs/ http://jsfiddle.net/MKFLs/

<!DOCTYPE html>
<html>
  <head>
    <title>Chrome localStorage Test</title>
    <script type="text/javascript" >

      var handle_storage = function () {
        alert('storage event');
      };

      window.addEventListener("storage", handle_storage, false);

    </script>
  </head>
  <body>
    <button id="add" onclick="localStorage.setItem('a','test')">Add</button>
    <button id="clear" onclick="localStorage.clear()">Clear</button>
  </body>
</html>

编辑: 顺便说一句,我在这里用 MS 打开了一个错误。https://connect.microsoft.com/IE/feedback/details/798684/ie-localstorage-event-misfired https://connect.microsoft.com/IE/feedback/details/798684/ie-localstorage-event-misfired

也许不会被关闭......


将脚本更改为以下内容可防止处理焦点窗口中的任何存储事件。

这并不完全是您所要求的,因为我相信这需要对浏览器进行补丁,但它会导致 IE 9/10 符合规范,同时对其他浏览器(全局和侦听器除外)没有不利影响。

<script type="text/javascript" >
      var focused;

      window.addEventListener('focus', function(){focused=1;}, false);
      window.addEventListener('blur', function(){focused=0;}, false);

      var handle_storage = function (e) {
        if(!focused)
          alert("Storage",focused);
      };

      window.addEventListener("storage", handle_storage, false);

</script>

See 这把小提琴 http://jsfiddle.net/MKFLs/7/以获得更新的、一致的行为。

编辑:以下方法也可以工作并避免侦听器,但以运行时检查窗口焦点为代价:

<script type="text/javascript" >

      var handle_storage = function (e) {
        if(!document.hasFocus())
          alert("Storage");
      };

      window.addEventListener("storage", handle_storage, false);

</script>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

IE localStorage 事件失火 的相关文章