创建自定义"console"对象以在浏览器中与自定义调试器的 Web 控制台进行交互



浏览器提供的Javascriptconsole对象上的Mozilla Developer Network页面显示:"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等工具在登录控制台时提供的行号/文件信息。我能找到的最匹配的答案是:拦截web浏览器控制台消息,但它并没有通过自定义控制台对象与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: '33[m',
RED: '33[31m',
GREEN: '33[32m',
BLUE: '33[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');

最新更新