How can I use console logging in Internet Explorer

2019-01-04 21:47发布

Is there a console logger for IE? I'm trying to log a bunch of tests/assertions to the console but I can't do this in IE.

9条回答
ゆ 、 Hurt°
2楼-- · 2019-01-04 22:07

For IE8 or console support limited to console.log (no debug, trace, ...) you can do the following:

  • If console OR console.log undefined: Create dummy functions for console functions (trace, debug, log, ...)

    window.console = { debug : function() {}, ...};

  • Else if console.log is defined (IE8) AND console.debug (any other) is not defined: redirect all logging functions to console.log, this allows to keep those logs !

    window.console = { debug : window.console.log, ...};

Not sure about the assert support in various IE versions, but any suggestions are welcome.

查看更多
乱世女痞
3楼-- · 2019-01-04 22:08

In his book, "Secrets of Javascript Ninja", John Resig (creator of jQuery) has a really simple code which will handle cross-browser console.log issues. He explains that he would like to have a log message which works with all browsers and here is how he coded it:

function log() {
  try {
    console.log.apply(console, arguments);
  } catch(e) {
  try {
    opera.postError.apply(opera, arguments);
  }
  catch(e) {
    alert(Array.prototype.join.call( arguments, " "));
  }
}
查看更多
闹够了就滚
4楼-- · 2019-01-04 22:15

There is Firebug Lite which gives a lot of Firebug functionality in IE.

查看更多
甜甜的少女心
5楼-- · 2019-01-04 22:18

You can use cross-browser wrapper: https://github.com/MichaelZelensky/log.js

查看更多
家丑人穷心不美
6楼-- · 2019-01-04 22:20

Since version 8, Internet Explorer has its own console, like other browsers. However, if the console is not enabled, the console object does not exist and a call to console.log will throw an error.

Another option is to use log4javascript (full disclosure: written by me), which has its own logging console that works in all mainstream browsers, including IE >= 5, plus a wrapper for the browser's own console that avoids the issue of an undefined console.

查看更多
爷、活的狠高调
7楼-- · 2019-01-04 22:24

Extremely important if using console.log() in production:

if you end up releasing console.log() commands to production you need to put in some kind of fix for IE - because console is only defined when in F12 debugging mode.

if (typeof console == "undefined") {
    this.console = { log: function (msg) { alert(msg); } };
}

[obviously remove the alert(msg); statement once you've verified it works]

See also 'console' is undefined error for Internet Explorer for other solutions and more details

查看更多
登录 后发表回答