Javascript HTML5 / JS 存储事件处理程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3055013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:07:47  来源:igfitidea点击:

HTML5 / JS storage event handler

javascriptjavascript-eventshtmlevent-handlingaddeventlistener

提问by Ken

I'm using safari webkit's engine together with HTML5 and JS to create an offline application now I'm using the sessionStorage array to store status of my application(simulation).

我正在使用 safari webkit 的引擎以及 HTML5 和 JS 来创建一个离线应用程序,现在我正在使用 sessionStorage 数组来存储我的应用程序(模拟)的状态。

the storage data works fine with the inspector the functions work fine it's the event handler that isn't responding

存储数据与检查器一起工作正常 功能工作正常 事件处理程序没有响应

the test preformd by Anuragat http://jsfiddle.net/pvRgH/also doesn't work here

Anuraghttp://jsfiddle.net/pvRgH/执行的测试在这里也不起作用

window.addEventListener('storage', storageEventHandler, false);
function storageEventHandler(evt){
    alert("storage event called key: " + evt.key );
    switch(evt.key){
        case 'bat1':
        case 'bat2': batteryDCMeter(); break;
        case 'extPowerOn': rechargeBattery(); break;
    }   
}

function load()
{
    dashcode.setupParts();
    //set HTML 5 key/value's
    sessionStorage.setItem('bat1', 'OFF');
    sessionStorage.setItem('bat2', 'OFF');
    sessionStorage.setItem('bat1DC', '26.2');
    sessionStorage.setItem('bat2DC', '26.2');
}

function bat1OnOff(event)
{
    if(sessionStorage['bat1'] == 'OFF'){
        sessionStorage['bat1'] = 'ON';
    }else{
        sessionStorage['bat1'] = "OFF";
    }
}


function bat2OnOff(event)
{
    if(sessionStorage['bat2'] == 'OFF'){
        sessionStorage['bat2'] = 'ON';
    }else{
        sessionStorage['bat2'] = "OFF";
    }
}

回答by jmease

Storage event handlers only fire if the storage event is triggered from another window.

存储事件处理程序仅在存储事件是从另一个窗口触发时触发。

How can I get an event to fire every time localStorage is updated in Safari 5+?

每次在 Safari 5+ 中更新 localStorage 时,如何才能触发事件?

回答by Anurag

Could you provide some more code for how you are storing the keys? It works for me on Safari - http://jsfiddle.net/pvRgH/

您能否提供更多关于如何存储密钥的代码?它在 Safari 上对我有用 - http://jsfiddle.net/pvRgH/

回答by chenhui5416

the 'storage' event occurred by the other tab in the browser. When you change the storage in one page and addEventLister also in this page , the window can not catch the message.

浏览器中的另一个选项卡发生了“存储”事件。当您更改一页中的存储并在此页中添加EventLister 时,窗口无法捕获消息。

for example

例如

You have two page, pageOne change the storage , pageTwo will catch the 'storage' message and handle this, but pageOne couldn't catch the message.

您有两个页面, pageOne 更改 storage , pageTwo 将捕获“存储”消息并处理此消息,但 pageOne 无法捕获该消息。