Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

localStorage eventHandler Doesn't Get Called

Tags:

html

Here is my code:

<script type="text/javascript">
    function getLocalStorage() {
        try {
            if (!! window.localStorage) return window.localStorage;
        } catch(e) {
            return undefined;
        }
    }

    function getAddEventListener() {
        try {
            if( !! window.addEventListener ) return window.addEventListener;
        } catch(e) {
            return undefined;
        }
    }

    function eventHandler(e) {
        alert("here we are = " + e.storageArea.traveler);
    }       

    function testStorage() {    
        var db = getLocalStorage();
        var addEL = getAddEventListener();

        if(addEL) {
          addEL('storage', eventHandler, false);
        } else {
            alert('This browser does not support event listeners');
        }

        db.setItem('traveler', 'Bill');
        db.setItem('destination', 'Ventura');
        db.setItem('transportation', 'Airplane');

        document.getElementById('results').innerHTML = db.getItem('destination');
    }   
</script>

</head>

<body onload="testStorage();">
  <div id="results"> </div>
</body>

</html>

It successfully insert items in the local storage and display result in 'results'-element, but eventHandler doesn't work. I refresh the browser windows and don't see any alert messages. Why?

like image 782
ceth Avatar asked Sep 15 '11 09:09

ceth


1 Answers

Because storage events don't work for same window/tab. They are fired only for other windows/tabs that use same localStorage. Try opening two separat tabs and in one insert some data to the localStorage.

Here is a similar question that explains how localStorage event works.

like image 177
antyrat Avatar answered Nov 09 '22 12:11

antyrat