每次在Safari 5+中更新localStorage时,如何获得一个事件触发? [英] How can I get an event to fire every time localStorage is updated in Safari 5+?

查看:147
本文介绍了每次在Safari 5+中更新localStorage时,如何获得一个事件触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着按照 Safari开发人员网站上的示例



文档建议添加一个事件侦听器所以:

  window.addEventListener('storage',storage_handler,false); 

然后设置您的处理程序函数,如下所示:

 函数storage_handler(evt)
{
alert('修改过的键是'+ evt.key);
alert('原始值为'+ evt.oldValue);
alert('新值是'+ evt.newValue);
alert('进行更改的页面的URL是'+ evt.url');
alert('进行更改的窗口是'+ evt.source);
}

但是我似乎无法让这段代码在我的机器上工作OS X 10.6,Safari 5.01)以及我的iPhone 3GS(iOS 4.02)上的Safari。

这篇文章提供了一个单独的方法:

  window.onload = function(){
...
document.body.setAttribute(onstorage,handleOnStorage(););
}

function handleOnStorage(){
if(window.event&& window.event.key.indexOf(index ::)== 0){
$(stats)。innerHTML =;
displayStats();
}
}

但是我还没有碰运气。



我做错了什么?这是一个错误吗?

解决方案

经过进一步调查(并在朋友的帮助下),我发现storage_handler方法被调用当本地存储值的值在当前窗口或选项卡中的页面上发生变化时,而当它在另一个选项卡中发生变化时不是这样。

例如,如果我有两个选项卡打开,并在每个选项卡的页面中都有控件来更改本地存储设置,然后当我在第一个选项卡中打开控件时,会在另一个选项卡中调用storage_handler方法。


I have tried to follow the examples on the Safari Developer Site.

The documentation suggests adding an event listener like so:

window.addEventListener('storage', storage_handler, false);

And then setting your handler function like this:

function storage_handler(evt)
{
    alert('The modified key was '+evt.key);
    alert('The original value was '+evt.oldValue);
    alert('The new value is '+evt.newValue);
    alert('The URL of the page that made the change was '+evt.url);
    alert('The window where the change was made was '+evt.source);
}

But I can't seem to get this code to work on my machine (OS X 10.6, Safari 5.01) nor on Safari on my iPhone 3GS (iOS 4.02).

This article offers a separate method:

window.onload = function() {
    ...
    document.body.setAttribute("onstorage", "handleOnStorage();");
}

function handleOnStorage() {
    if (window.event && window.event.key.indexOf("index::") == 0){
        $("stats").innerHTML = "";
        displayStats();
    }
}

But I haven't had any luck with that either.

Am I doing something wrong? Is this a bug?

解决方案

After investigating further (and with the help from a friend) I discovered that the storage_handler method is called not when the value of a localstorage value changes on the page in my current window or tab, but when it changes in another tab.

For example, if I have the two tabs open, and have controls in the pages in each tab to change localstorage settings, then when I hit the control in the first tab, the storage_handler method is called in the other tab.

这篇关于每次在Safari 5+中更新localStorage时,如何获得一个事件触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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