3

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

  1. Why did it throw the error?
  2. How do I apply get Proxy on window.location in Javascript?
Community
  • 1
  • 1

1 Answers1

5

Why did it throw the error?

It's for the same reason why proxies are incompatible with Sets or with Maps: 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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375