6

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?

kumarharsh
  • 18,961
  • 8
  • 72
  • 100
ceth
  • 44,198
  • 62
  • 180
  • 289
  • 2
    What happens if you use `window.addEventListener('storage', eventHandler, false)`, rather than `addEL('storage', eventHandler, false)`. – Paul Grime Sep 15 '11 at 09:31

1 Answers1

12

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.

Community
  • 1
  • 1
antyrat
  • 27,479
  • 9
  • 75
  • 76