Skip to content

Instantly share code, notes, and snippets.

@mynameislau
Created October 25, 2019 12:04
Show Gist options
  • Save mynameislau/b7eabfcdc0a17ac41cdc0b974f94d807 to your computer and use it in GitHub Desktop.
Save mynameislau/b7eabfcdc0a17ac41cdc0b974f94d807 to your computer and use it in GitHub Desktop.
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);
};
}
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment