25

I added an eventListener to the window DOM-Object and want to keep track of the changes made to localStorage.

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>

    <script language="JavaScript"><!-- 
        window.addEventListener('storage', storageEventHandler, false);
        function storageEventHandler(evt){
            console.log("oldValue: " + evt.oldValue );
            console.log("storage event called key: " + evt.key );
            console.log("newValue: " + evt.newValue );

        }
        $(document).ready(function(event) {
            $('#link1').click(function(event){
                event.preventDefault();
                localStorage.setItem('page', 2000);
                console.log(localStorage.getItem('page'));
            });
            $('#link2').click(function(event){
                event.preventDefault();
                localStorage.setItem('page', 998);
                console.log(localStorage.getItem('page'));

            });

         });
    </script>
</head>
</html>

Somehow the storageEventHandler is never called even though the localStorage value is changed when I click link1 or link2. Any help is much appreciated.

Waynn Lue
  • 11,344
  • 8
  • 51
  • 76
doemsche
  • 892
  • 2
  • 12
  • 25

2 Answers2

47

Some browsers don't support the storage event, and most of the browsers that do support it will only call it when the storage is changed by a different window/tab. So, open your page up in two windows. Click the links in one window and you will probably see the event in the other.

The assumption is that your page will already know all interactions with localStorage in its own window and only needs notification when a different window changes things. This, of course, is a foolish assumption. But, localStorage is a new thing. Hopefully, they'll eventually figure it all out.

Mir-Ismaili
  • 13,974
  • 8
  • 82
  • 100
Nathan Bubna
  • 6,823
  • 2
  • 35
  • 36
30

The storage event handler will only affect other windows. Whenever something changes in one window inside localStorage all the other windows are notified about it and if any action needs to be taken it can be achieved by a handler function listening to the storage event.

For same window you have to manually call the storageEventHandler function after localStorage.setItem() is called to achieve the same behaviour in the same window.

subham.saha1004
  • 794
  • 8
  • 6