How to test if an object is a Proxy?

后端 未结 13 2122
予麋鹿
予麋鹿 2020-11-30 07:23

I would like to test if a JavaScript object is a Proxy. The trivial approach

if (obj instanceof Proxy) ...

doesn\'t work here, nor does tra

相关标签:
13条回答
  • 2020-11-30 07:57

    Matthew Brichacek and David Callanan give good answers for Proxy you create yourself but if it is not the case here are some additions

    Imagine you have an external function creating Proxy that you can't modify

    const external_script = ()=>{
        return new Proxy({a:5},{})
    }
    

    Before any externals code executions, we can redefine the proxy constructor and use a WeakSet to store proxy as Matthew Brichacek does. I don't use a class because otherwise Proxy will have a prototype and it will be detectable that Proxy has been changed.

    const proxy_set = new WeakSet()
    window.Proxy = new Proxy(Proxy,{
          construct(target, args) {
            const proxy = new target(...args)
            proxy_set.add(proxy)
            return proxy
          }
    })
    const a = external_script()
    console.log(proxy_set.has(a)) //true
    

    Same method but with Symbol like David Callanan

      const is_proxy = Symbol('is_proxy')
      const old_Proxy = Proxy
      const handler = {
        has (target, key) {
          return (is_proxy === key) || (key in target)
        }
      }
      window.Proxy = new Proxy(Proxy,{
          construct(target, args) {
              return new old_Proxy(new target(...args), handler)
          }
      })
      const a = external_script()
      console.log(is_proxy in a) //true
    

    I think the first is better because you only change the constructor while the second creates a proxy of a proxy while the purpose of the question was to avoid this.

    It does not work if the proxy is created inside an iframe because we only have redefined the proxy for the current frame.

    0 讨论(0)
提交回复
热议问题