Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
651 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...