In attempting to put HTML5 storage to use for cross-window configuration synchronization purposes, I just performed some
tests on what works how in different browsers, and how it relates to the
not-yet-frozen HTML5 specs, which at present declare that storage events should work like this:
On changing a value in
localStorage
(running
localStorage.setItem()
,
localStorage.removeItem()
, or
localStorage.clear()
, and presumably their javascript setter / deletion conveinence API:s, where supported), an
e.type === "storage"
event should be fired in all
other windows open to the same domain (e here being the event object seen by the event listener). (No specific mention forbids firing the same event in the same window, too, but it seems to be the intent to avoid that, to me, and is also the behaviour I would prefer myself.)
When an assignment (
localStorage.setItem()
), the
e.key
property should be the name of the key, the
e.oldValue
its former value, and
e.newValue
its new value.
When a deletion (
localStorage.removeItem()
),
e.newValue
should instead be the
null
value.
When a clear all event (
localStorage.clear()
),
e.key
,
e.oldValue
and
e.newValue
should all be the
null
value.
No browser seems to do quite that yet, but Safari and Chrome are at least rather close. My tests have covered Firefox 3.5.7, Safari 4.0.4 (6531.21.10), WebKit 4.0.4 (6531.21.10, r53119), Google Chrome 4.0.249.49 (35163) beta, Chromium 4.0.267.0 (34084), all on MacOS X (10.6). They all ignore which window triggered the storage event (= fire the event in all applicable windows).
Firefox, sadly, never provides either of the three properties mentioned above.
Chrome, Chromium, Safari and WebKit all provide all three, but instead of setting the
e.key
to
null
for the clear event, it gets set to the empty string. The rest works beautifully, though.
Whether the clear event fires when clearing an already empty
localStorage
varies a little -- Firefox and Safari will, the others don't.
Neither browser fires events when deleting an already deleted value, but Firefox fires events when setting a property to the same value it already had (the others don't).
I spent a minimal amount of time peeking at what IE8 does and how, but didn't get it working. It supposedly supports at least the localStorage function-calling API, according to
MSDN. The tests above may miss something subtle, maybe with how to use attachEvent instead of the W3C standard addEventListener (don't ask me why they still
don't support that).