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 = new Proxy(location, {
get: (target, name) => {
console.log(name, target, "PROX");
return target[name];
}
});
The error messages were:
VM3495:3 Symbol(Symbol.toPrimitive) Location {…} "PROX"
VM3495:3 toString Location {…} PROX
Uncaught TypeError: Illegal invocation at :1:10
- Why did it throw the error?
- How do I apply
get
Proxy onwindow.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 = new Proxy(location, {
get: (target, name) => {
console.log(name, target, "PROX");
return target[name];
}
});
The error messages were:
VM3495:3 Symbol(Symbol.toPrimitive) Location {…} "PROX"
VM3495:3 toString Location {…} PROX
Uncaught TypeError: Illegal invocation at :1:10
- Why did it throw the error?
- How do I apply
get
Proxy onwindow.location
in Javascript?
-
I'm not sure whether
location
can be assigned to. – Bergi Commented Aug 30, 2017 at 17:32 - @Bergi It can’t! The code was from my try to do so, though. – Константин Ван Commented Apr 22, 2022 at 21:20
1 Answer
Reset to default 6Why did it throw the error?
It's for the same reason why proxies are inpatible 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:
new Proxy(location, {
get: (target, name) => {
console.log(name, target, "PROX");
return typeof 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.