Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

localStorage eventListener is not called [duplicate]

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.

like image 671
doemsche Avatar asked Mar 20 '11 19:03

doemsche


2 Answers

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.

like image 162
Nathan Bubna Avatar answered Nov 09 '22 03:11

Nathan Bubna


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.

like image 21
subham.saha1004 Avatar answered Nov 09 '22 02:11

subham.saha1004