Jak wydrukować komunikaty debugowania w konsoli JavaScript Google Chrome?

Jak wydrukować komunikaty debugowania w konsoli JavaScript Google Chrome?

Należy pamiętać, że konsola JavaScript nie jest taka sama jak Debugger JavaScript; mają one różne składnie AFAIK, więc print polecenie w Debuggerze JavaScript nie będzie tutaj działać. W konsoli JavaScript, print() wyśle parametr do drukarki.

Author: Peter Mortensen, 2008-10-20

15 answers

Wykonywanie następującego kodu z paska adresu przeglądarki:

javascript: console.log(2);

Pomyślnie wyświetla wiadomość na "konsoli JavaScript" w Google Chrome.

 600
Author: Sergey Ilinsky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-10-20 10:20:23

Ulepszając pomysł Andru, możesz napisać skrypt, który tworzy funkcje konsoli, jeśli nie istnieją:

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

Następnie należy użyć któregokolwiek z poniższych:

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

Funkcje te będą rejestrować różne typy elementów (które mogą być filtrowane na podstawie dziennika, informacji, błędu lub ostrzeżenia) i nie będą powodować błędów, gdy konsola nie jest dostępna. Funkcje te będą działać w konsolach Firebug i Chrome.

 167
Author: Delan Azabani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-05-03 11:01:31

Po prostu dodaj fajną funkcję, za którą wielu deweloperów tęskni:

console.log("this is %o, event is %o, host is %s", this, e, location.host);

To jest magiczny %o zrzut klikalny i głęboko przeglądany zawartość obiektu JavaScript. %s został pokazany tylko dla zapisu.

Również to jest fajne też:

console.log("%s", new Error().stack);

, który daje podobny do Javy ślad stosu do punktu wywołania new Error() (w tym ścieżkę do pliku i numer linii!).

Zarówno %o jak i new Error().stack są dostępne w Chrome i Firefox!

Także do śledzenia stosu w Firefoksie:

console.trace();

Jako https://developer.mozilla.org/en-US/docs/Web/API/console mówi.

Szczęśliwego hakowania!

UPDATE : niektóre biblioteki są pisane przez złych ludzi, którzy redefiniują obiekt console do własnych celów. Aby przywrócić oryginalną przeglądarkę console po załadowaniu biblioteki, użyj:

delete console.log;
delete console.warn;
....

Zobacz pytanie o przepełnienie stosu Przywracanie konsoli.log().

 47
Author: gavenkoa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:17:58

Tylko szybkie ostrzeżenie - jeśli chcesz przetestować w Internet Explorerze bez usuwania całej konsoli.log () ' s, będziesz musiał użyć Firebug Lite albo dostaniesz jakieś niezbyt przyjazne błędy.

(lub stwórz własną konsolę.log (), która po prostu zwraca false.)

 17
Author: Andru,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-20 11:16:04

Oto krótki skrypt, który sprawdza, czy konsola jest dostępna. Jeśli nie jest, próbuje załadować Firebug i jeśli Firebug nie jest dostępny, ładuje Firebug Lite. Teraz możesz używać console.log W dowolnej przeglądarce. Smacznego!

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.
}
 17
Author: Vegar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-20 11:18:44

Oprócz odpowiedzi delana Azabaniego , lubię dzielić się swoją console.js i używam w tym samym celu. Stworzyłem konsolę noop używając tablicy nazw funkcji, co jest moim zdaniem bardzo wygodnym sposobem na to, i zająłem się Internet Explorerem, który ma funkcję console.log, ale nie console.debug:

// Create a noop console object if the browser doesn't provide one...
if (!window.console){
  window.console = {};
}

// Internet Explorer has a console that has a 'log' function, but no 'debug'. To make console.debug work in Internet Explorer,
// We just map the function (extend for info, etc. if needed)
else {
  if (!window.console.debug && typeof window.console.log !== 'undefined') {
    window.console.debug = window.console.log;
  }
}

// ... and create all functions we expect the console to have (taken from Firebug).
var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

for (var i = 0; i < names.length; ++i){
  if(!window.console[names[i]]){
    window.console[names[i]] = function() {};
  }
}
 13
Author: Tim Büthe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:02:41

Lub użyj tej funkcji:

function log(message){
    if (typeof console == "object") {
        console.log(message);
    }
}
 12
Author: Tarek Saied,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-20 11:25:00

Oto moja klasa pakowania konsoli. Daje mi to również wyjście z zakresu, aby ułatwić życie. Zwróć uwagę na użycie localConsole.debug.call() tak, że localConsole.debug działa w zakresie wywołującej klasy, zapewniając dostęp do jej metody toString.

localConsole = {

    info: function(caller, msg, args) {
        if ( window.console && window.console.info ) {
            var params = [(this.className) ? this.className : this.toString() + '.' + caller + '(), ' + msg];
            if (args) {
                params = params.concat(args);
            }
            console.info.apply(console, params);
        }
    },

    debug: function(caller, msg, args) {
        if ( window.console && window.console.debug ) {
            var params = [(this.className) ? this.className : this.toString() + '.' + caller + '(), ' + msg];
            if (args) {
                params = params.concat(args);
            }
            console.debug.apply(console, params);
        }
    }
};

someClass = {

    toString: function(){
        return 'In scope of someClass';
    },

    someFunc: function() {

        myObj = {
            dr: 'zeus',
            cat: 'hat'
        };

        localConsole.debug.call(this, 'someFunc', 'myObj: ', myObj);
    }
};

someClass.someFunc();

To daje wyjście tak w Firebug:

In scope of someClass.someFunc(), myObj: Object { dr="zeus", more...}

Lub Chrome:

In scope of someClass.someFunc(), obj:
Object
cat: "hat"
dr: "zeus"
__proto__: Object
 7
Author: Bruce,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-20 11:24:24

Osobiście używam tego, co jest podobne do tarek11011:

// Use a less-common namespace than just 'log'
function myLog(msg)
{
    // Attempt to send a message to the console
    try
    {
        console.log(msg);
    }
    // Fail gracefully if it does not exist
    catch(e){}
}

Głównym punktem jest to, że jest to dobry pomysł, aby przynajmniej mieć trochę praktyki logowania innych niż tylko przyklejenie console.log() prawo do kodu JavaScript, ponieważ jeśli o tym zapomnisz, a to jest na stronie produkcyjnej, może potencjalnie złamać cały kod JavaScript dla tej strony.

 6
Author: cwd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-20 11:26:04

Możesz użyć console.log() jeśli masz debugowany kod w jakim edytorze oprogramowania masz i zobaczysz wynik najprawdopodobniej najlepszy dla mnie edytor (Google Chrome). Po prostu naciśnij F12 i naciśnij kartę konsola. Zobaczysz wynik. Szczęśliwego kodowania. :)

 4
Author: stryker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-20 11:26:28

Miałem wiele problemów z programistami sprawdzającymi konsolę.wypowiedzi. I, naprawdę nie lubię debugowania Internet Explorer, pomimo fantastycznych ulepszeń Internet Explorer 10 i Visual Studio 2012 , itp.

Więc nadpisałem sam obiekt konsoli... Dodałem flagę _ _ localhost, która zezwala na polecenia konsoli tylko wtedy, gdy na localhost. Dodałem również konsolę.() funkcji do przeglądarki Internet Explorer (która wyświetla alert() zamiast tego).

// Console extensions...
(function() {
    var __localhost = (document.location.host === "localhost"),
        __allow_examine = true;

    if (!console) {
        console = {};
    }

    console.__log = console.log;
    console.log = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__log === "function") {
                console.__log(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert(msg);
            }
        }
    };

    console.__info = console.info;
    console.info = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__info === "function") {
                console.__info(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert(msg);
            }
        }
    };

    console.__warn = console.warn;
    console.warn = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__warn === "function") {
                console.__warn(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert(msg);
            }
        }
    };

    console.__error = console.error;
    console.error = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__error === "function") {
                console.__error(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert(msg);
            }
        }
    };

    console.__group = console.group;
    console.group = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__group === "function") {
                console.__group(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert("group:\r\n" + msg + "{");
            }
        }
    };

    console.__groupEnd = console.groupEnd;
    console.groupEnd = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__groupEnd === "function") {
                console.__groupEnd(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert(msg + "\r\n}");
            }
        }
    };

    /// <summary>
    /// Clever way to leave hundreds of debug output messages in the code,
    /// but not see _everything_ when you only want to see _some_ of the
    /// debugging messages.
    /// </summary>
    /// <remarks>
    /// To enable __examine_() statements for sections/groups of code, type the
    /// following in your browser's console:
    ///       top.__examine_ABC = true;
    /// This will enable only the console.examine("ABC", ... ) statements
    /// in the code.
    /// </remarks>
    console.examine = function() {
        if (!__allow_examine) {
            return;
        }
        if (arguments.length > 0) {
            var obj = top["__examine_" + arguments[0]];
            if (obj && obj === true) {
                console.log(arguments.splice(0, 1));
            }
        }
    };
})();

Przykładowe użycie:

    console.log("hello");

Chrome/Firefox:

    prints hello in the console window.

Internet Explorer:

    displays an alert with 'hello'.
[6]}dla tych, którzy uważnie przyglądają się kodowi, odkryjesz konsolę.funkcja examine (). Stworzyłem to lata temu, aby pozostawić kod debugowania w niektórych obszarach wokół produktu, aby pomóc w rozwiązywaniu problemów QA /problemy z klientami. Na przykład zostawiłbym następującą linijkę w jakimś wydanym kodzie:
    function doSomething(arg1) {
        // ...
        console.examine("someLabel", arg1);
        // ...
    }

A następnie z wypuszczonego produktu, Wpisz w konsoli (lub pasku adresu poprzedzonym 'javascript:'):

    top.__examine_someLabel = true;

Wtedy zobaczę całą zalogowaną konsolę.polecenia examine (). To była fantastyczna Pomoc wiele razy.

 4
Author: kodybrown,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-20 11:32:55

Prosty Internet Explorer 7 i poniżej shim zachowujący numerację linii dla innych przeglądarek:

/* Console shim */
(function () {
    var f = function () {};
    if (!window.console) {
        window.console = {
            log:f, info:f, warn:f, debug:f, error:f
        };
    }
}());
 3
Author: dbrin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-20 11:34:28
console.debug("");

Za pomocą tej metody wyświetla tekst w konsoli w jasnym niebieskim kolorze.

Tutaj wpisz opis obrazka

 2
Author: Nicholas Smith,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-12 08:12:25

[[2]}dalsze ulepszanie pomysłów delana i Andru (dlatego ta odpowiedź jest wersją edytowaną); konsola.log prawdopodobnie istnieje, podczas gdy inne funkcje mogą nie istnieć, więc mają domyślną mapę do tej samej funkcji, co konsola.log....

Możesz napisać skrypt, który tworzy funkcje konsoli, jeśli nie istnieją:

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

Następnie należy użyć któregokolwiek z poniższych:

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

Funkcje te będą rejestrować różne typy elementów (które mogą być filtrowane na podstawie dziennika, informacji, błędu lub ostrzeżenia) i nie spowoduje błędów, gdy konsola nie jest dostępna. Funkcje te będą działać w konsolach Firebug i Chrome.

 1
Author: vogomatix,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-20 14:51:04

Mimo, że to pytanie jest stare i ma dobre odpowiedzi, chcę zapewnić aktualizację innych możliwości logowania.

Możesz również drukować z grupami:

console.group("Main");
console.group("Feature 1");
console.log("Enabled:", true);
console.log("Public:", true);
console.groupEnd();
console.group("Feature 2");
console.log("Enabled:", false);
console.warn("Error: Requires auth");
console.groupEnd();

Który drukuje:

Tutaj wpisz opis obrazka

To jest obsługiwane przez wszystkie główne przeglądarki zgodnie z ta strona : Tutaj wpisz opis obrazka

 0
Author: Daniel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-26 18:03:49