Reputation: 143
I want to redefine window.localStorage.setItem() so that it gets intercepted every time it's called anywhere on a webpage, and another version of this function is executed. I need to do this because I want to use a custom localStorage and so I need to add a third parameter which specifies where to save those data. I was reading about Javascript Proxies but I'm not sure whether they do what I want to accomplish. Does it make sense anyway? Can I even do something like this?
Upvotes: 0
Views: 94
Reputation: 24221
Yes, it's possible.
Although I would say it's not advised. Creating a wrapper function to do this would be better.
function mySetItem(key, value) {
console.log(key, value);
return localStorage.setItem(key, value);
}
But if you really want to intercept, you could do something like ->
const old = localStorage.setItem; //store old method
localStorage.setItem =
function (...args) {
console.log(args); //intercept, args
return old.apply(localStorage, arguments); //call native
}
Upvotes: 1