Proxy HTMLElement

前端 未结 1 1269
伪装坚强ぢ
伪装坚强ぢ 2021-01-13 07:46

I wanted to check what does a library do with video element I pass to it so I naively did this:

cosnt videoElement = new Proxy(document.querySelector(\'video         


        
1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-13 08:14

    As already mentioned in the comments, the Proxy object will not get automatically casted into Node when calling document.body.contains(proxy).

    Therefore, you can i.e. set a specific key that will return the proxy's target:

    const video = document.querySelector('video');
    const proxy = new Proxy(video, {
      get(target, key) {
            const value = video[key];
            if (value instanceof Function) {
            return value.bind(video);
            } else if (key == 'target') {
            return target;
          } else {
            return value;
            }
      },
      set(target, key, value) {
        target[key] = value;
        return true;
      }
    });
    

    And then you can do:

    console.log(document.body.contains(proxy.target));
    

    Edit:

    Is this really how it is supposed to be? (the document.body.contains(myProxyElement) part):

    Yes, I do not see any other way how to do this.

    Setting values to video element throwing when setting inside proxy seemed weird, is it a bug? (3rd point, kinda second too, I suppose it is connected):

    Since I am not able to reproduce this issue, it is hard to say. Maybe try to replace new Proxy(video, ... with new Proxy({}, ... and then set the video as proxy.video = video (you will have to also update the logic in the get and set) and see how that behaves?

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