javascript 在 Chrome 中拦截对 console.log 的调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9216441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Intercept calls to console.log in Chrome
提问by sprugman
I have a script that I can't change that makes a lot of console.log calls. I want to add another layer and respond if the calls contain certain strings. This works in FF, but throws an "Illegal invocation" error in Chrome on the 4th line:
我有一个无法更改的脚本,它会进行大量 console.log 调用。如果调用包含某些字符串,我想添加另一个层并做出响应。这适用于 FF,但在 Chrome 中的第 4 行引发“非法调用”错误:
var oldConsole = {};
oldConsole.log = console.log;
console.log = function (arg) {
oldConsole.log('MY CONSOLE!!');
oldConsole.log(arg);
}
Any ideas how to get around that? I also tried cloning the console...
任何想法如何解决这个问题?我也尝试克隆控制台...
回答by zzzzBov
You need to call console.log
in the context of console
for chrome:
您需要console.log
在console
for chrome的上下文中调用:
(function () {
var log = console.log;
console.log = function () {
log.call(this, 'My Console!!!');
log.apply(this, Array.prototype.slice.call(arguments));
};
}());
Modern language features can significantly simplify this snippet:
现代语言功能可以显着简化此代码段:
{
const log = console.log.bind(console)
console.log = (...args) => {
log('My Console!!!')
log(...args)
}
}
回答by rgthree
You can also use the same logic, but call it off the console object so the context is the same.
您也可以使用相同的逻辑,但在控制台对象中调用它,因此上下文是相同的。
if(window.console){
console.yo = console.log;
console.log = function(str){
console.yo('MY CONSOLE!!');
console.yo(str);
}
}
回答by Ludovic Feltz
I know it's an old post but it can be useful anyway as others solution are not compatible with older browsers.
我知道这是一篇旧帖子,但无论如何它都会很有用,因为其他解决方案与旧浏览器不兼容。
You can redefine the behavior of each functionof the console (and for all browsers) like this:
您可以像这样重新定义控制台(以及所有浏览器)的每个功能的行为:
// define a new console
var console = (function(oldCons){
return {
log: function(text){
oldCons.log(text);
// Your code
},
info: function (text) {
oldCons.info(text);
// Your code
},
warn: function (text) {
oldCons.warn(text);
// Your code
},
error: function (text) {
oldCons.error(text);
// Your code
}
};
}(window.console));
//Then redefine the old console
window.console = console;
回答by Devnegikec
With ES6 new spread operator you can write it like this
使用 ES6 新的扩展运算符,您可以这样编写
(function () {
var log = console.log;
console.log = function () {
log.call(this, 'My Console!!!', ...arguments);
};
}());
回答by NVRM
Can be simply:
可以简单地:
console.log = (m) => terminal.innerHTML = JSON.stringify(m)
#terminal {background: black; color:chartreuse}
$ > <span id="terminal"></span>
<hr>
<button onclick="console.log('Hello world!!')">3V3L</button>
<button onclick="console.log(document)">3V3L</button>
<button onclick="console.log(Math.PI)">3V3L</button>