Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 947
Jason Avatar asked Aug 25 '10 04:08

Jason


People also ask

Does Safari support localStorage?

In short, you can't, but you can set a cookie via JavaScript 😉 Safari on iOS supports localStorage, but in Private Mode it simply throws an error when you try to save anything to it, which is not great. Also it breaks the behaviour of your app on iPhones and iPads.

What is storage event?

The storage event occurs when there is a change in the window's change area. Note: The storage event is only triggered when a window other than itself makes the changes.


1 Answers

I realize this is asking about Safari but, per the Mozilla Developer Network, the StorageEvent is only fired if the web storage object is changed from outside the page, e.g., in another tab.

https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API

Scroll down to "Responding to storage changes with the StorageEvent".

(I would have added this as a comment to the accepted answer but I don't have the rep for that.)

like image 196
nklatt Avatar answered Nov 08 '22 14:11

nklatt