How do I print debug messages in the Google Chrome JavaScript Console?

前端 未结 14 819
清酒与你
清酒与你 2020-11-27 08:54

How do I print debug messages in the Google Chrome JavaScript Console?

Please note that the JavaScript Console is not the same as the JavaScript Debugger; they have

相关标签:
14条回答
  • 2020-11-27 09:45

    Improving further on ideas of Delan and Andru (which is why this answer is an edited version); console.log is likely to exist whilst the other functions may not, so have the default map to the same function as console.log....

    You can write a script which creates console functions if they don't exist:

    if (!window.console) console = {};
    console.log = console.log || function(){};
    console.warn = console.warn || console.log;  // defaults to log
    console.error = console.error || console.log; // defaults to log
    console.info = console.info || console.log; // defaults to log
    

    Then, use any of the following:

    console.log(...);
    console.error(...);
    console.info(...);
    console.warn(...);
    

    These functions will log different types of items (which can be filtered based on log, info, error or warn) and will not cause errors when console is not available. These functions will work in Firebug and Chrome consoles.

    0 讨论(0)
  • Here is a short script which checks if the console is available. If it is not, it tries to load Firebug and if Firebug is not available it loads Firebug Lite. Now you can use console.log in any browser. Enjoy!

    if (!window['console']) {
    
        // Enable console
        if (window['loadFirebugConsole']) {
            window.loadFirebugConsole();
        }
        else {
            // No console, use Firebug Lite
            var firebugLite = function(F, i, r, e, b, u, g, L, I, T, E) {
                if (F.getElementById(b))
                    return;
                E = F[i+'NS']&&F.documentElement.namespaceURI;
                E = E ? F[i + 'NS'](E, 'script') : F[i]('script');
                E[r]('id', b);
                E[r]('src', I + g + T);
                E[r](b, u);
                (F[e]('head')[0] || F[e]('body')[0]).appendChild(E);
                E = new Image;
                E[r]('src', I + L);
            };
            firebugLite(
                document, 'createElement', 'setAttribute', 'getElementsByTagName',
                'FirebugLite', '4', 'firebug-lite.js',
                'releases/lite/latest/skin/xp/sprite.png',
                'https://getfirebug.com/', '#startOpened');
        }
    }
    else {
        // Console is already available, no action needed.
    }
    
    0 讨论(0)
提交回复
热议问题