开发者

localStorage eventHandler Doesn't Get Called

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜