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}`); 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); }; } }) });

About Ricard Torres

Senior Front-end Software Engineer from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.

@ricard_dev @ricard_dev

📝 Blog 🎙 Podcast

Leave a Reply

Add <code> Some Code </code> by using this tags.

*
*