alias to chrome console.log

自作多情 提交于 2019-12-27 11:43:29

问题


I would like to know why the follow code doesn't work in the Google Chrome:

// creates a xss console log

var cl = ( typeof( console ) != 'undefined' ) ? console.log : alert;
cl('teste');

output: Uncaught TypeError: Illegal invocation

thanks.


回答1:


When you write cl();, you're calling log in the global context.

Chrome's console.log doesn't want to be called on the window object.

Instead, you can write

cl = function() { return console.log.apply(console, arguments); };

This will call log in the context of console.




回答2:


https://groups.google.com/a/chromium.org/d/msg/chromium-bugs/gGVPJ1T-qA0/F8uSupbO2R8J

Apparently you can also defined log:

 log = console.log.bind(console);

and then the line numbers also work




回答3:


Unfortunately @SLaks answer isnt applied to IE because it uses window-object as context in console.log-method.

I would be suggest another way that doesnt depend on browser:

!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.
};


来源:https://stackoverflow.com/questions/5133649/alias-to-chrome-console-log

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!