我需要拦截对某些DOM API函数的调用,并将它们的参数存储为副作用。例如,假设我对函数getElementsByTagName
和getElementById
感兴趣。见下面的例子:
"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"]
答案 0 :(得分:0)
如果只想拦截对这两个函数的调用,则不需要使用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)