本文介绍了在 Chrome 中拦截对 console.log 的调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个无法更改的脚本,它会进行很多 console.log 调用.如果调用包含某些字符串,我想添加另一个层并做出响应.这在 Firefox 中有效,但会抛出Illegal invocation";Chrome 中的第 4 行错误:

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 Firefox, but throws an "Illegal invocation" error in Chrome on the 4th line:

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...

推荐答案

你需要在console的上下文中调用console.log for chrome:

You need to call console.log in the context of 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)
  }
}

这篇关于在 Chrome 中拦截对 console.log 的调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 14:58