Javascript chrome console.log的别名
我想知道为什么以下代码在Google Chrome中不起作用:Javascript chrome console.log的别名,javascript,exception,google-chrome,Javascript,Exception,Google Chrome,我想知道为什么以下代码在Google Chrome中不起作用: // creates a xss console log var cl = ( typeof( console ) != 'undefined' ) ? console.log : alert; cl('teste'); 输出:未捕获类型错误:非法调用 谢谢。当你写cl()时,您正在全局上下文中调用log Chrome的console.log不希望在窗口对象上被调用 相反,你可以写作 cl = function() { retu
// creates a xss console log
var cl = ( typeof( console ) != 'undefined' ) ? console.log : alert;
cl('teste');
输出:未捕获类型错误:非法调用
谢谢。当你写cl()时
,您正在全局上下文中调用log
Chrome的console.log
不希望在窗口
对象上被调用
相反,你可以写作
cl = function() { return console.log.apply(console, arguments); };
这将在控制台的上下文中调用log
显然,您还可以定义日志:
log = console.log.bind(console);
然后行号也起作用不幸的是@SLaks answer不适用于IE,因为它在console.log-method中使用窗口对象作为上下文
我建议另一种不依赖于浏览器的方式:
!window.console && (console = {});
console.debug = console.debug || $.noop;
console.info = console.info || $.noop;
console.warn = console.warn || $.noop;
console.log = console.log || $.noop;
var src = console, desc = {};
desc.prototype = src;
console = desc;
desc.log = function(message, exception) {
var msg = message + (exception ? ' (exception: ' + exception + ')' : ''), callstack = exception && exception.stack;
src.log(msg);
callstack && (src.log(callstack));
//logErrorUrl && $.post(logErrorUrl, { message: msg + (callstack || '') }); // Send clientside error message to serverside.
};
@augustowebd:关于“上下文”的更多信息,我写了几篇可能有用的博客文章:这有一个缺点,就是没有在Web Inspector中记录正确的行号。我刚刚遇到了一个类似的问题,我想覆盖console.log
方法(捕获并发送输出)。我的解决方案是在控制台
对象上声明别名。大致:console.\uu log=console.log;console.log=function(){{uuuu console.log.apply(console,arguments);}代码>。我爱你,这几年来一直让我发疯。终于找到了解决办法!谢谢:D