Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break on localStorage changes

I'm looking for a way to break on any localStorage changes. I have found that there are some mysterious entries that I have no idea where that is coming from and I would like the debugger to break on any changes so that I can inspect the code. This includes:

localStorage.someKey = someValue;
localStorage["someKey"] = someValue;
localStorage.setItem("someKey", someValue);

Since there are so many ways to alter/create an entry in localStorage, simply overriding .setItem and do debugger; will not work. Any idea is appreciated.

like image 571
Derek 朕會功夫 Avatar asked Mar 04 '18 05:03

Derek 朕會功夫


1 Answers

Not on the native localStorage object, but on a proxied version:

Object.defineProperty(window, 'localStorage', {
  configurable: true,
  enumerable: true,
  value: new Proxy(localStorage, {
    set: function (ls, prop, value) {
      console.log(`direct assignment: ${prop} = ${value}`);
      debugger;
      ls[prop] = value;
      return true;
    },
    get: function(ls, prop) {
      // The only property access we care about is setItem. We pass
      // anything else back without complaint. But using the proxy
      // fouls 'this', setting it to this {set: fn(), get: fn()}
      // object.
      if (prop !== 'setItem') {
        if (typeof ls[prop] === 'function') {
          return ls[prop].bind(ls);
        } else {
          return ls[prop];
        }
      }
      // If you don't care about the key and value set, you can
      // drop a debugger statement here and just
      // "return ls[prop].bind(ls);"
      // Otherwise, return a custom function that does the logging
      // before calling setItem:
      return (...args) => {
        console.log(`setItem(${args.join()}) called`);
        debugger;
        ls.setItem.apply(ls, args);
      };
    }
  })
});

We create a Proxy for window.localStorage that will intercept property assignment (handling the localStorage.someKey = someValue and localStorage["someKey"] = someValue cases) and property access (handling the localStorage.setItem("someKey", someValue) case).

Now we need to point window.localStorage at our proxy, but it's read-only. However, it's still configurable! We can redefine its value with Object.defineProperty.

like image 164
AuxTaco Avatar answered Oct 11 '22 01:10

AuxTaco