Which browsers support console.log()?

后端 未结 8 1514
生来不讨喜
生来不讨喜 2020-12-03 13:12

Do all browsers support this? I would like to output an error using console.log() but was wondering if this supported by all browsers?

console.         


        
相关标签:
8条回答
  • 2020-12-03 13:55

    No, not all browsers support console.log as it is not part of the standard and is an extension of the DOM and thus you should not count on its presence. To make your code resilient you should assume it does not exist and code accordingly.

    0 讨论(0)
  • 2020-12-03 13:55

    Most browsers do, however Internet Explorer 9 has issues with it where it wont run any javascript unless you have the debug window open. Took us hours to find the solution to that problem.

    0 讨论(0)
  • 2020-12-03 13:56

    It is now August 2015, and I think the current answer to this question is:

    All major browsers on mobile and desktop support console.log. (caniuse)

    It is not part of any standard, but it is now an expected deliverable of a complete modern browser.

    However:

    If you need to support old browsers (IE<10), more mobile browsers, or users running experimental browsers, then it might be a good idea to use a polyfill (1,2,3,4) to ensure window.console exists.

    It might not work in WebWorkers on all browsers. (MDN)

    In UC Browser and Opera Mini the functions will run, but you won't see the output. (caniuse)

    But for the vast majority of web users now, we can assume console.log will work as expected.

    0 讨论(0)
  • 2020-12-03 14:03

    Make a wrapper function:

    function log(text) {
      if (window.console) {
         window.console.log(text);
      }
    }
    
    0 讨论(0)
  • 2020-12-03 14:07

    This code will check to see if the function exists and create a dummy in case it does not. Credit: StackOverflow

    if (!window.console) window.console = {};
    if (!window.console.log) window.console.log = function () { };
    
    0 讨论(0)
  • 2020-12-03 14:14

    Although not all browsers support that, it can be accomplished with a small chunk of code.

    In his book, "Secrets of Javascript Ninja", John Resig (creator of jQuery) has a really simple code which will handle cross-browser console.logissues. 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, " "));
      }
    }
    
    0 讨论(0)
提交回复
热议问题