Skip to content

Instantly share code, notes, and snippets.

@radum
Created September 24, 2018 14:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save radum/564c277226b9370fc25a16546989de07 to your computer and use it in GitHub Desktop.
Save radum/564c277226b9370fc25a16546989de07 to your computer and use it in GitHub Desktop.
localStorage 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 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];
}
}
console.log('setItem called');
debugger;
return ls[prop].bind(ls);
}
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment