Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind to localStorage change event using jQuery for all browsers?

How do I bind a function to the HTML5 localStorage change event using jQuery?

$(function () {

  $(window).bind('storage', function (e) {
    alert('storage changed');
  });

  localStorage.setItem('a', 'test');

});

I've tried the above but the alert is not showing.

Update: It works in Firefox 3.6 but it doesn't work in Chrome 8 or IE 8 so the question should be more 'How to bind to localStorage change event using jQuery for all browsers?'

like image 805
David Glenn Avatar asked Jan 12 '11 17:01

David Glenn


2 Answers

It turns out that this is actually working correctly and I have misinterpreted the specification

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

In other words, a storage event is fired on every window/tab except for the one that updated the localStorage object and caused the event.

So the event was not fired because I only had one window/tab open. If I place the above code in a page and open the page in two tabs I would see the event fired in the second tab.

This answer on the problem contains more details.

like image 71
David Glenn Avatar answered Oct 21 '22 21:10

David Glenn


Here's how to do it in JQuery:

 $(window).bind('storage', function (e) {
     console.log(e.originalEvent.key, e.originalEvent.newValue);
 });

Accessing e.key directly does not work. You need to use e.originalEvent.key.

Some browsers will only send storage notifications to other tabs, and some won't. (Firefox will send storage events to its own tab, but with key set to null, it seems like).

like image 13
Flimm Avatar answered Oct 21 '22 19:10

Flimm