Co się stało z konsolą.Zaloguj się IE8?

Author: Doug Harris, 2009-03-27

17 answers

Jeszcze lepsze dla fallback jest to:


   var alertFallback = true;
   if (typeof console === "undefined" || typeof console.log === "undefined") {
     console = {};
     if (alertFallback) {
         console.log = function(msg) {
              alert(msg);
         };
     } else {
         console.log = function() {};
     }
   }

 226
Author: jpswain,
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
2011-05-11 16:33:17

Konsola.dziennik jest dostępny tylko po otwarciu narzędzi programistycznych (F12, aby przełączyć go otwarte i zamknięte). Zabawne jest to, że po otwarciu można go zamknąć, a następnie opublikować do niego za pomocą konsoli.rejestruj połączenia, a te będą widoczne po ponownym otwarciu. Myślę, że jest to swego rodzaju błąd i może być naprawiony, ale zobaczymy.

Prawdopodobnie użyję czegoś takiego:

function trace(s) {
  if ('console' in self && 'log' in console) console.log(s)
  // the line below you might want to comment out, so it dies silent
  // but nice for seeing when the console is available or not.
  else alert(s)
}

I jeszcze prostsze:

function trace(s) {
  try { console.log(s) } catch (e) { alert(s) }
}
 256
Author: Mister Lucky,
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
2012-06-25 15:03:28

Oto moje spojrzenie na różne odpowiedzi. Chciałem zobaczyć zalogowane wiadomości, nawet jeśli nie miałem otwartej konsoli IE podczas ich uruchamiania, więc wciskałem je do tablicy console.messages, którą tworzę. Dodałem również funkcję console.dump() ułatwiającą przeglądanie całego dziennika. console.clear() opróżni kolejkę komunikatów.

To rozwiązanie "obsługuje" również inne metody Konsolowe (które, jak sądzę, wszystkie pochodzą z Firebug Console API)

Wreszcie To rozwiązanie jest w forma IIFE , więc nie zanieczyszcza globalnego zasięgu. Argument funkcji awaryjnej jest zdefiniowany na dole kodu.

Po prostu upuszczam go do mojego pliku master JS, który jest zawarty na każdej stronie, i o tym zapominam.

(function (fallback) {    

    fallback = fallback || function () { };

    // function to trap most of the console functions from the FireBug Console API. 
    var trap = function () {
        // create an Array from the arguments Object           
        var args = Array.prototype.slice.call(arguments);
        // console.raw captures the raw args, without converting toString
        console.raw.push(args);
        var message = args.join(' ');
        console.messages.push(message);
        fallback(message);
    };

    // redefine console
    if (typeof console === 'undefined') {
        console = {
            messages: [],
            raw: [],
            dump: function() { return console.messages.join('\n'); },
            log: trap,
            debug: trap,
            info: trap,
            warn: trap,
            error: trap,
            assert: trap,
            clear: function() { 
                  console.messages.length = 0; 
                  console.raw.length = 0 ;
            },
            dir: trap,
            dirxml: trap,
            trace: trap,
            group: trap,
            groupCollapsed: trap,
            groupEnd: trap,
            time: trap,
            timeEnd: trap,
            timeStamp: trap,
            profile: trap,
            profileEnd: trap,
            count: trap,
            exception: trap,
            table: trap
        };
    }

})(null); // to define a fallback function, replace null with the name of the function (ex: alert)

Niektóre dodatkowe informacje

Linia var args = Array.prototype.slice.call(arguments); tworzy tablicę z obiektu arguments. Jest to wymagane, ponieważ arguments tak naprawdę nie jest tablicą .

trap() jest domyślnym narzędziem obsługi dowolnej funkcji API. I pass argumenty do message, aby uzyskać dziennik argumentów, które zostały przekazane do dowolnego wywołania API (nie tylko console.log).

Edit

Dodałem dodatkową tablicę console.raw, która przechwytuje argumenty dokładnie tak, jak przekazałem do trap(). Zdałem sobie sprawę, że args.join(' ') konwertuje obiekty na łańcuch znaków "[object Object]", co czasami może być niepożądane. Dzięki bfontaine za sugestię .

 55
Author: Walter Stabosz,
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:10:29

Warto zauważyć, że console.log w IE8 nie jest prawdziwą funkcją Javascript. Nie obsługuje metod apply Ani call.

 52
Author: James Wheare,
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
2009-08-11 18:20:43

Zakładając, że nie zależy ci na wycofaniu alertu, oto jeszcze bardziej zwięzły sposób obejścia niedociągnięć przeglądarki Internet Explorer:

var console=console||{"log":function(){}};
 44
Author: Leif Wickland,
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
2012-04-12 18:37:41

Bardzo podoba mi się podejście napisane przez "orange80". Jest elegancki, ponieważ można go ustawić raz i zapomnieć.

Inne podejścia wymagają zrobienia czegoś innego (za każdym razem nazywaj coś innego niż zwykły console.log()), co jest tylko prośbą o kłopoty... wiem, że w końcu zapomnę.

Posunąłem się o krok dalej, zawijając kod w funkcję narzędzia, którą można wywołać raz na początku javascript, w dowolnym miejscu, o ile jest to przed każdym logowaniem. (I ' m instalacja tego w produkcie routera danych zdarzeń mojej firmy. Pomoże to uprościć projekt nowego interfejsu administracyjnego między przeglądarkami.)

/**
 * Call once at beginning to ensure your app can safely call console.log() and
 * console.dir(), even on browsers that don't support it.  You may not get useful
 * logging on those browers, but at least you won't generate errors.
 * 
 * @param  alertFallback - if 'true', all logs become alerts, if necessary. 
 *   (not usually suitable for production)
 */
function fixConsole(alertFallback)
{    
    if (typeof console === "undefined")
    {
        console = {}; // define it if it doesn't exist already
    }
    if (typeof console.log === "undefined") 
    {
        if (alertFallback) { console.log = function(msg) { alert(msg); }; } 
        else { console.log = function() {}; }
    }
    if (typeof console.dir === "undefined") 
    {
        if (alertFallback) 
        { 
            // THIS COULD BE IMPROVED… maybe list all the object properties?
            console.dir = function(obj) { alert("DIR: "+obj); }; 
        }
        else { console.dir = function() {}; }
    }
}
 25
Author: Chris Janicki,
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
2011-09-12 14:05:31

Jeśli masz "undefined" na całej konsoli.rejestruj połączenia, to prawdopodobnie oznacza, że nadal masz załadowany Stary firebuglite (firebug.js). Nadpisze wszystkie poprawne funkcje konsoli IE8./ align = "left" / I tak mi się to przydarzyło.

Sprawdź, czy inny kod nadpisuje obiekt konsoli.

 8
Author: user168290,
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
2009-10-20 19:56:09

Najlepszym rozwiązaniem dla każdej przeglądarki, która nie ma konsoli jest:

// Avoid `console` errors in browsers that lack a console.
(function() {
    var method;
    var noop = function () {};
    var methods = [
        'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
        'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
        'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
        'timeStamp', 'trace', 'warn'
    ];
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];

        // Only stub undefined methods.
        if (!console[method]) {
            console[method] = noop;
        }
    }
}());
 5
Author: Vinícius Moraes,
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-02-20 19:51:49

Jest tyle odpowiedzi. Moim rozwiązaniem było:

globalNamespace.globalArray = new Array();
if (typeof console === "undefined" || typeof console.log === "undefined") {
    console = {};
    console.log = function(message) {globalNamespace.globalArray.push(message)};   
}

W skrócie, jeśli konsola.log nie istnieje (lub w tym przypadku nie jest otwarty), a następnie przechowuje log w globalnej tablicy przestrzeni nazw. W ten sposób nie jesteś nękany milionami alertów i nadal możesz przeglądać dzienniki za pomocą otwartej lub zamkniętej Konsoli programisty.

 3
Author: calcazar,
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-06-23 11:29:04
if (window.console && 'function' === typeof window.console.log) {
    window.console.log(o);
}
 2
Author: Balázs Németh,
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
2011-04-01 13:50:18

Oto moje "IE proszę nie crash"

typeof console=="undefined"&&(console={});typeof console.log=="undefined"&&(console.log=function(){});
 2
Author: BrunoLM,
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
2013-11-13 02:02:41

Znalazłem to na github :

// usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function f() {
    log.history = log.history || [];
    log.history.push(arguments);
    if (this.console) {
        var args = arguments,
            newarr;
        args.callee = args.callee.caller;
        newarr = [].slice.call(args);
        if (typeof console.log === 'object') log.apply.call(console.log, console, newarr);
        else console.log.apply(console, newarr);
    }
};

// make it safe to use console.log always
(function(a) {
    function b() {}
    for (var c = "assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","), d; !! (d = c.pop());) {
        a[d] = a[d] || b;
    }
})(function() {
    try {
        console.log();
        return window.console;
    } catch(a) {
        return (window.console = {});
    }
} ());
 1
Author: Sam Jones,
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
2013-08-23 11:44:05

Używam podejścia Waltera z góry (patrz: https://stackoverflow.com/a/14246240/3076102 )

Mieszam w roztworze, które znalazłem tutaj https://stackoverflow.com/a/7967670 aby poprawnie wyświetlać Obiekty.

Oznacza to, że funkcja trap staje się:

function trap(){
    if(debugging){
        // create an Array from the arguments Object           
        var args = Array.prototype.slice.call(arguments);
        // console.raw captures the raw args, without converting toString
        console.raw.push(args);
        var index;
        for (index = 0; index < args.length; ++index) {
            //fix for objects
            if(typeof args[index] === 'object'){ 
                args[index] = JSON.stringify(args[index],null,'\t').replace(/\n/g,'<br>').replace(/\t/g,'&nbsp;&nbsp;&nbsp;');
            }
        }
        var message = args.join(' ');
        console.messages.push(message);
        // instead of a fallback function we use the next few lines to output logs
        // at the bottom of the page with jQuery
        if($){
            if($('#_console_log').length == 0) $('body').append($('<div />').attr('id', '_console_log'));
            $('#_console_log').append(message).append($('<br />'));
        }
    }
} 

Mam nadzieję, że to pomoże: -)

 1
Author: Raymond Elferink,
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 11:47:16

Działa w IE8. Otwórz Narzędzia programistyczne IE8, naciskając F12.

>>console.log('test')
LOG: test
 0
Author: Konstantin Tarkus,
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
2009-03-27 15:40:23

Lubię tę metodę (używając Doc ready jquery)... pozwala używać konsoli nawet w ie... haczyk polega tylko na tym, że musisz przeładować stronę, jeśli otworzysz narzędzia dev ie po załadowaniu strony...

Może być slicker biorąc pod uwagę wszystkie funkcje, ale używam tylko log więc to jest to, co robię.

//one last double check against stray console.logs
$(document).ready(function (){
    try {
        console.log('testing for console in itcutils');
    } catch (e) {
        window.console = new (function (){ this.log = function (val) {
            //do nothing
        }})();
    }
});
 0
Author: user3560902,
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-04-22 14:38:53

Oto wersja, która będzie logować się do konsoli, gdy narzędzia programistyczne są otwarte, a nie gdy są zamknięte.

(function(window) {

   var console = {};
   console.log = function() {
      if (window.console && (typeof window.console.log === 'function' || typeof window.console.log === 'object')) {
         window.console.log.apply(window, arguments);
      }
   }

   // Rest of your application here

})(window)
 0
Author: George Reith,
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-10-02 00:41:10

Stwórz własną konsolę w html .... ;-) Można to nadrukować, ale można zacząć od:

if (typeof console == "undefined" || typeof console.log === "undefined") {
    var oDiv=document.createElement("div");
    var attr = document.createAttribute('id'); attr.value = 'html-console';
    oDiv.setAttributeNode(attr);


    var style= document.createAttribute('style');
    style.value = "overflow: auto; color: red; position: fixed; bottom:0; background-color: black; height: 200px; width: 100%; filter: alpha(opacity=80);";
    oDiv.setAttributeNode(style);

    var t = document.createElement("h3");
    var tcontent = document.createTextNode('console');
    t.appendChild(tcontent);
    oDiv.appendChild(t);

    document.body.appendChild(oDiv);
    var htmlConsole = document.getElementById('html-console');
    window.console = {
        log: function(message) {
            var p = document.createElement("p");
            var content = document.createTextNode(message.toString());
            p.appendChild(content);
            htmlConsole.appendChild(p);
        }
    };
}
 0
Author: Alexandre Assouad,
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-10-13 15:34:06