簡體   English   中英

創建自定義“控制台”對象以與瀏覽器中的 Web 控制台交互以進行自定義調試器

[英]Creating a custom "console" object to interact with Web Console in browser for custom debugger

瀏覽器提供的 Javascript console對象上的 Mozilla 開發者網絡頁面說:“ Note: At least in Firefox, if a page defines a console object, that object overrides the one built into Firefox. ”。 有沒有辦法覆蓋這個對象,但仍然與瀏覽器的Web 控制台交互?

一個用例是攔截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()很好奇。 我還想找到一個與 Firebug 等現有 Web 控制台/工具一起使用的解決方案,而不是創建自定義瀏覽器擴展或 Firebug 插件,但如果有人知道現有的解決方案,我會對它們感興趣。

顯然是這樣的:

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

不會工作並導致無限遞歸。

這很簡單,只需在覆蓋之前保存對(原始)控制台的引用:

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

你可以做:

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');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM