IE localStorage event misfired

耗尽温柔 提交于 2020-12-01 03:49:28

问题


Within Internet Explorer 9 & 10, the localStorage implementation fires events unexpectedly (great thread here: Bug with Chrome's localStorage implementation?)

Does anybody know of a way to stop the storage event from firing on tabs that initiated the change within internet explorer?

For example the following shouldn't show an alert when the add button is clicked, but it does in IE:

fiddle: 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>

EDIT: On a side note, I've opened a bug with MS here. https://connect.microsoft.com/IE/feedback/details/798684/ie-localstorage-event-misfired

Maybe it won't get closed.....


回答1:


Changing your script to the following prevents the handling of any storage events in the focused window.

This isn't precisely what you asked, as I believe that would require a patch to the browser, but it causes IE 9/10 to conform to the spec while having no adverse effects on other browsers (other than the global and listeners).

<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 this fiddle for the updated, conforming behavior.

Edit: The following also works and avoids the listeners at the cost of a runtime check of window focus:

<script type="text/javascript" >

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

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

</script>


来源:https://stackoverflow.com/questions/18476564/ie-localstorage-event-misfired

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!