I am trying to override the dot notation for access to localStorage. I already managed to override the getItem and setItem methods as described here: Is it possible to override Local Storage and Session Storage separately in HTML5?
Now I tried to create a Proxy to also catch the dot access, but since I seem to be unable to overwrite the localStorage object as tried here
localStorage = new Proxy(localStorage, {
get: function(target, name) {
if (!(name in target)) {
console.log("Getting non-existent property '" + name + "'");
return undefined;
}
return '123';
},
set: function(target, name, value) {
if (!(name in target)) {
console.log("Setting non-existent property '" + name + "', initial value: " + value);
}
target[name] = value;
}
});
Now when I try it I still get test instead of 123:
localStorage.testKey = "test";
alert(localStorage.testKey)
Override the method on localStorage. If we look closely, setItem and getItem are inherited from Storage __proto__ pseudo property. Then we directly override the above localStorage. __proto__ method. This implements the real override of the setItem() method.
Local storage is bound to the domain, so in regular case the user cannot change it on any other domain or on localhost. It is also bound per user/browser, i.e. no third party has access to ones local storage. Nevertheless local storage is in the end a file on the user's file system and may be hacked. Save this answer.
The storage is bound to the origin (domain/protocol/port triplet). That is, different protocols or subdomains infer different storage objects, they can't access data from each other.
In any browser, the localStorage is limited to storing only 5Mb of data. Cannot be used by web workers. This means that if you want to do more complex applications, using background processing to improve performance, you can't use localStorage because it is not available.
If you define the getter on localStorage it should work:
Object.defineProperty(window, "localStorage", new (function () {
this.get = function() {
console.log("I'm getting called");
}
})());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With