Skip to content

Instantly share code, notes, and snippets.

@skooch
Created April 4, 2024 02:02
Show Gist options
  • Save skooch/a50dd90b8260313db1ece508c0958530 to your computer and use it in GitHub Desktop.
Save skooch/a50dd90b8260313db1ece508c0958530 to your computer and use it in GitHub Desktop.
localStorage.getItem proxy
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 getItem. We pass
// anything else back without complaint. But using the proxy
// fouls 'this', setting it to this {set: fn(), get: fn()}
// object.
if (prop !== 'getItem') {
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(`getItem(${args.join()}) called`);
// debugger;
ls.getItem.apply(ls, args);
};
}
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment