【问题标题】:Creating a custom "console" object to interact with Web Console in browser for custom debugger在浏览器中为自定义调试器创建自定义“控制台”对象以与 Web 控制台交互
【发布时间】:2012-11-19 05:55:51
【问题描述】:

Mozilla 开发者网络 page 在浏览器提供的 Javascript console 对象上说:“Note: At least in Firefox, if a page defines a console object, that object overrides the one built into Firefox.”。有什么办法可以覆盖这个对象,但还是和浏览器的Web Console交互?

一个用例是拦截 console.log() 调用并做一些额外的事情或采用不同的参数,例如日志分类,同时保留通过 Firebug 或 Google Chrome Inspect Element 等工具登录到控制台时提供的行号/文件信息.我能找到的最接近的匹配答案是:Intercepting web browser console messages,但它不会通过自定义控制台对象与 Web 控制台进行交互,也不会使用自定义的调试服务,如

debug.log = function(string, logLevel) {
    checkLogLevel(logLevel); // return false if environment log setting is below logLevel 
    var changedString = manipulate(string); 
    console.log(changedString); 
}

不保留调用debug.log() 的函数的行号/文件源。一种选择是使用console.trace() 做一些事情并在跟踪堆栈上爬上一层,但我很好奇首先扩展console.log()。我还想找到一个与现有 Web 控制台/工具(如 Firebug)一起使用的解决方案,而不是创建自定义浏览器扩展或 Firebug 插件,但如果有人知道现有的解决方案,我会对它们感兴趣。

显然是这样的:

    console = {
        log: function (string) {
            console.log('hey!');
        }
    }
    console.log('hey!');

不起作用并导致无限递归。

【问题讨论】:

标签: javascript debugging firebug google-chrome-devtools


【解决方案1】:

这很简单,只需在覆盖之前保存对(原始)控制台的引用:

var originalConsole = window.console;
console = {
    log: function(message) {
        originalConsole.log(message);
        // do whatever custom thing you want
    }
}

【讨论】:

  • 当然!那很漂亮。不幸的是,它最终与定义自定义调试服务相同,因为报告的行号/文件仍然是单根 originalConsole.log(message);调用,而不是调用者的行号,如 console.log();。我正在寻找某种方式与 Web 控制台进行交互,就像 console.log() 一样,尽管它可能不存在。
  • 查看getfirebug.com/wiki/index.php/Console_API。该链接专门用于 Firebug,但它应该让您对使用控制台对象时可以/不可以有一个不错的了解。
【解决方案2】:

你可以这样做:

var colors = {
  DEFAULT: '\033[m',
  RED: '\033[31m',
  GREEN: '\033[32m',
  BLUE: '\033[34m'
};
var print = {
  out: function(message) {
    console.log(message);
  },
  read: function(message) {
    prompt(message + ' ');
  },
  color: function(message, color) {
    if (color == 'RED') {
      console.log(`${colors.RED}${message}${colors.DEFAULT}`);
    }
    else if (color == 'GREEN') {
      console.log(`${colors.GREEN}${message}${colors.DEFAULT}`);
    }
    else if (color == 'BLUE') {
      console.log(`${colors.BLUE}${message}${colors.DEFAULT}`);
    }
    else {
      console.log(`${colors.RED}ValueError: \"${color}\" is not in the colors set.`);
    }
  }
};

您可以使用以下方法对其进行测试:

print.out('Hello World!');
print.read('Hello World!');
print.color('Hello World!', 'RED');
print.color('Hello World!', 'GREEN');
print.color('Hello World!', 'BLUE');

【讨论】:

    猜你喜欢
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-02
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    相关资源
    最近更新 更多