【发布时间】:2016-10-14 09:23:38
【问题描述】:
我需要拦截对某些 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"]
【问题讨论】:
-
我不知道为什么,但听起来你在做坏事......
-
@evolutionxbox
bad thing是什么意思? -
你试图通过拦截这些调用来解决的actual problem 是什么?
标签: javascript node.js ecmascript-6 jsdom es6-proxy