如何打破localStorage的变化

Der*_*會功夫 5 javascript debugging google-chrome google-chrome-devtools

我正在寻找一种打破任何localStorage变化的方法.我发现有一些神秘的条目,我不知道它来自哪里,我希望调试器能够打破任何更改,以便我可以检查代码.这包括:

localStorage.someKey = someValue;
localStorage["someKey"] = someValue;
localStorage.setItem("someKey", someValue);
Run Code Online (Sandbox Code Playgroud)

由于在localStorage中有很多方法可以改变/创建一个条目,所以简单地覆盖.setItem并且做debugger;不起作用.任何想法都表示赞赏.

Aux*_*aco 13

我很惊讶我有这个工作,但是是的!

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);
      };
    }
  })
});
Run Code Online (Sandbox Code Playgroud)

我们创建一个localStoragefor Proxy将拦截属性赋值(处理window.localStoragelocalStorage.someKey = someValue案例)和属性访问(处理localStorage["someKey"] = someValue案例).

现在我们需要指向localStorage.setItem("someKey", someValue)我们的代理,但它是只读的.但是,它仍然是可配置的!我们可以重新定义它的价值window.localStorage.