How to break on LocalStorage changes

If you're debugging a LocalStorage issue and want to use a call stack to know what or who is triggering a localstorage get or set you can define a proxy function.

The following snippet will overwrite the window.localStorage

It has the same functions but adds a console.log and debugger before them.

Object.defineProperty(window, 'localStorage', {
  configurable: true,
  enumerable: true,
  value: new Proxy(localStorage, {
    set: function (ls, prop, value) {
      console.log(`direct assignment: ${prop} = ${value}`);
      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`);
        ls.setItem.apply(ls, args);
});Code language: JavaScript (javascript)


  1. sorcererinferior says:

    🌈Very Cool!🌈

Leave a Reply

Your email address will not be published. Required fields are marked *