How Do I Apply `get` Proxy On `window.location` In Javascript?
I'm using Chrome 60. I've just tried to apply a get Proxy on window.location. It worked for the first two reference, however, then it failed with Illegal invocation error: location
Solution 1:
Why did it throw the error?
It's for the same reason why proxies are incompatible with Set
s or with Map
s: They are native objects, and their methods (like toString
in your example) expect to be called on exactly such a native object with the respective internal slots, not a proxy.
How do I apply get Proxy on
window.location
in Javascript?
You need to bind all methods that the get
traps intercepts to the target:
newProxy(location, {
get: (target, name) => {
console.log(name, target, "PROX");
returntypeof target[name] == "function"
? target[name].bind(target)
: target[name];
}
});
However, that still doesn't change that you cannot replace the window.location
global with your own implementation. It's a non-configurable property, and assigning to it will cause a navigation not write to the property.
Post a Comment for "How Do I Apply `get` Proxy On `window.location` In Javascript?"