【问题标题】:IE localStorage event misfiredIE localStorage 事件未触发
【发布时间】:2013-08-30 20:34:44
【问题描述】:

在 Internet Explorer 9 和 10 中,localStorage 实现意外触发事件(此处的精彩线程:Bug with Chrome's localStorage implementation?

有人知道如何阻止storage 事件在启动 Internet Explorer 更改的选项卡上触发吗?

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

小提琴: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

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

【问题讨论】:

  • @EricLaw 感谢您的编辑 :)

标签: javascript html internet-explorer local-storage


【解决方案1】:

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

这并不是您所问的,因为我认为这需要对浏览器进行修补,但它会导致 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>

请参阅 this fiddle 了解更新后的一致行为。

编辑:以下方法也有效,并以运行时检查窗口焦点为代价避免了侦听器:

<script type="text/javascript" >

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

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

</script>

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多