最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How do I apply `get` Proxy on `window.location` in Javascript? - Stack Overflow

programmeradmin1浏览0评论

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?

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?
Share edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Aug 30, 2017 at 16:52 Константин ВанКонстантин Ван 14.9k8 gold badges75 silver badges87 bronze badges 2
  • 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
Add a ment  | 

1 Answer 1

Reset to default 6

Why did it throw the error?

It's for the same reason why proxies are inpatible 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.

发布评论

评论列表(0)

  1. 暂无评论