CodeKaro CodeKaro - 1 month ago 17
jQuery Question

Listen to localstorage change event

Is there a way to add a change event listener to browser localstorage items.

I have a standalone app that makes changes to localstorage to which I want my backbone view to listen to and accordingly perform some actions.

I couldn't find anything on the internet except for a way to do it in jQuery:

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

Answer

jQuery can bind to the storage event (in the exact way you wrote), however there are a few things you must note:

  1. You must run the code behind a real ip/domain (you can read more my explanation here)
  2. The storage event will fire on every open tab except the current tab (which mean - if you have only 1 open tab, and you make some change to the local-storage in that tab - the even will not fire). More information here.

Regarding backbone - try something like this:

var SomeView = Backbone.View.extend({
    initialize:function() {
        $(window).on("storage", this.handleLocalStorageChange)
    }
});