localStorage eventHandler不会被调用 [英] localStorage eventHandler Doesn't Get Called

查看:69
本文介绍了localStorage eventHandler不会被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

<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>

它成功地将项目插入本地存储,并以'results'元素显示结果,但是eventHandler不起作用.我刷新了浏览器窗口,但是没有看到任何警报消息.为什么?

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?

推荐答案

因为存储事件不适用于同一窗口/选项卡.仅针对使用相同 localStorage 的其他窗口/选项卡触发它们.尝试打开两个分离选项卡,然后在其中之一中向 localStorage 中插入一些数据.

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.

这是一个类似的问题,说明了 localStorage >活动有效.

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

这篇关于localStorage eventHandler不会被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆