Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IE localStorage event misfired

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.....

like image 496
Jesse Avatar asked Aug 27 '13 22:08

Jesse


1 Answers

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>
like image 79
Wyatt Avatar answered Nov 16 '22 05:11

Wyatt