How to break on localStorage changes

≡放荡痞女 提交于 2020-06-12 02:53:50

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/49092423/how-to-break-on-localstorage-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!