拦截对 DOM API 函数的调用

Intercept calls to DOM API functions

我需要拦截对某些 DOM API 函数的调用并将它们的参数存储为副作用。例如,假设我对函数 getElementsByTagNamegetElementById 感兴趣。请参见下面的示例:

"use strict";
const jsdom = require("jsdom");
let document = jsdom.jsdom("<html><head></head><body><div id='foo'><div></div></div></body></html>");
let cpool = {ids: [], tags: []};
let obj = document.getElementById("foo");
// --> cpool = {ids: ["foo"], tags: []}
obj.getElementsByTagName("div"); 
// --> cpool = {ids: ["foo"], tags: ["div"]}

一个重要说明是我正在使用node.js并且document对象是由jsdom 库。到目前为止,我试图利用 ES6 代理来修改上述 DOM 函数的行为。

这就是我尝试代理 document 对象以捕获所有方法调用的方式。我想知道是否以及如何使用这种技术或其他一些技术来解决我的问题。

let documentProxy = new Proxy(document, {
    get(target, propKey, receiver) {
        return function (...args) {
            Reflect.apply(target, propKey, args);
            console.log(propKey + JSON.stringify(args));
            return result;
        };
    }
});    
documentProxy.getElementById("foo");
// --> getElementById["foo"]

如果只想拦截对这两个函数的调用,则不需要使用Proxy。您可以只存储原始函数的副本,并使用保存参数的函数覆盖要拦截调用的函数,然后调用原始函数。

const cpool = {ids: [], tags: []}

;(getElementsByTagNameCopy => {
  document.getElementsByTagName = tag => {
    cpool.tags.push(tag)
    return Reflect.apply(getElementsByTagNameCopy, document, [tag])
  }
})(document.getElementsByTagName)

;(getElementsByTagNameCopy => {
  Element.prototype.getElementsByTagName = function(tag) {
    cpool.tags.push(tag)
    return Reflect.apply(getElementsByTagNameCopy, this, [tag])
  }
})(Element.prototype.getElementsByTagName)

;(getElementByIdCopy => {
  document.getElementById = id => {
    cpool.ids.push(id)
    return Reflect.apply(getElementByIdCopy, document, [id])
  }
})(document.getElementById)

console.log(document.getElementsByTagName('body'))
console.log(document.getElementById('whatever'))
console.log(document.body.getElementsByTagName('div'))
console.log(cpool)