localStorage: Cannot get storage event to fire

Hello,

I’m attempting to track changes to values I’ve stored in the localStorage object. From everything thing I’ve read, this is done by adding a “storage” event listener to the window object but the test file I made doesn’t seem to fire the event. I was under the impression that there was pretty good support for this (although I do realize the spec is still under revision). Am doing anything obviously wrong?


  if(localStorage) {
    // Set Item
    button1 = document.createElement("input");
    button1.value = "write to localStorage";
    button1.setAttribute("type","button");
    document.body.appendChild(button1);

    button1.addEventListener("click",function() {
      console.log("attempting to set item");
      localStorage.setItem("newItem","asdfasdfasdf");
    },false);

    // Clear All
    button2 = document.createElement("input");
    button2.value = "clear localStorage";
    button2.setAttribute("type","button");
    document.body.appendChild(button2);

    button2.addEventListener("click",function() {
      console.log("attempting to clear all");
      localStorage.clear();
    },false);

    window.addEventListener("storage",function(e) {
      console.log("storage event fired... woohoo!");
      console.log(e);
    },true);
  }

I create two buttons on the page - the first to write a value to localStorage (which works) and the second to clear all values from localStorage (also works). The problem is the event just does not want to fire for me. Even if I set the event on the window’s “onstorage” property rather than use addEventListener, no event fires. I’ve tried in the most recent Chrome, Firefox and Safari browsers.

Any ideas? Thanks in advance.
Brad.

This [Dive Into HTML5 info from the Storage page seems to confirm what should happen.

The storage event is fired on the window object whenever setItem(), removeItem(), or clear() is called and actually changes something. For example, if you set an item to its existing value or call clear() when there are no named keys, the storage event will not fire, because nothing actually changed in the storage area.

How odd that it’s not.

Ahh, clarity comes from the sessionstorage attribute section of the spec.

When the setItem(), removeItem(), and clear() methods are called on a Storage object x that is associated with a session storage area, if the methods did something, then in every Document object whose Window object’s sessionStorage attribute’s Storage object is associated with the same storage area, other than x, a storage event must be fired

It seems that multiple window objects are required then.