在 Javascript 中记录方法调用和 属性 访问
Record Method calls and Property access in Javascript
我想知道是否有任何方法可以记录 Javascript 中的所有方法调用(带参数)和 属性 访问。
例如:
1- 我想在 document.createElement("CANVAS");
创建 canvas 时收到通知
2- 当脚本试图访问 navigator.plugins
或 window.screen
.
时,我需要得到通知
提前致谢。
您可以为函数添加钩子,例如:
let calls = (function(){
let calls = 0;
let fun = document.createElement;
document.createElement = function(){
calls++;
return fun.apply(document, arguments);
}
return ()=>calls;
})();
let canvas = document.createElement("canvas");
document.body.appendChild(canvas);
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgb(200, 0, 0)';
ctx.fillRect(10, 10, 50, 50);
console.log("calls of document.createElement:", calls());
注意事项:不要尝试在 SO 代码片段中从挂钩的 document.createElement
执行 console.log
,因为 console.log
本身被剪断引擎挂钩以构建元素。 .
另一种方法是为对象设置代理:
Object.defineProperty(window, "navigator", {
value: new Proxy(window.navigator, {
get: function(target, name) {
console.log("navigator property", name, "is read")
return target[name];
}
})
});
console.log("plugins:", window.navigator.plugins);
我想知道是否有任何方法可以记录 Javascript 中的所有方法调用(带参数)和 属性 访问。
例如:
1- 我想在 document.createElement("CANVAS");
创建 canvas 时收到通知
2- 当脚本试图访问 navigator.plugins
或 window.screen
.
提前致谢。
您可以为函数添加钩子,例如:
let calls = (function(){
let calls = 0;
let fun = document.createElement;
document.createElement = function(){
calls++;
return fun.apply(document, arguments);
}
return ()=>calls;
})();
let canvas = document.createElement("canvas");
document.body.appendChild(canvas);
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgb(200, 0, 0)';
ctx.fillRect(10, 10, 50, 50);
console.log("calls of document.createElement:", calls());
注意事项:不要尝试在 SO 代码片段中从挂钩的 document.createElement
执行 console.log
,因为 console.log
本身被剪断引擎挂钩以构建元素。 .
另一种方法是为对象设置代理:
Object.defineProperty(window, "navigator", {
value: new Proxy(window.navigator, {
get: function(target, name) {
console.log("navigator property", name, "is read")
return target[name];
}
})
});
console.log("plugins:", window.navigator.plugins);