문제

Google Chrome JavaScript 콘솔에서 디버그 메시지를 어떻게 인쇄합니까?

JavaScript 콘솔은 JavaScript 디버거와 동일하지 않습니다. 그들은 다른 구문을 가지고 있습니다 인쇄 JavaScript Debugger의 명령은 여기서 작동하지 않습니다. JavaScript 콘솔에서 print() 매개 변수를 프린터로 보냅니다.

도움이 되었습니까?

해결책

브라우저 주소 표시 줄에서 다음 코드 실행 :

javascript: console.log(2);

Google Chrome의 "JavaScript 콘솔"에 메시지를 성공적으로 인쇄합니다.

다른 팁

Andru의 아이디어를 향상 시키면 콘솔 기능이 존재하지 않으면 스크립트를 작성할 수 있습니다.

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

그런 다음 다음 중 하나를 사용하십시오.

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

이 기능은 다른 유형의 항목 (로그, 정보, 오류 또는 경고를 기반으로 필터링 할 수 있음)을 기록하며 콘솔을 사용할 수없는 경우 오류가 발생하지 않습니다. 이러한 기능은 Firebug 및 Chrome 콘솔에서 작동합니다.

많은 개발자들이 놓친 멋진 기능을 추가하십시오.

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

이것은 마법입니다 %o 덤프 클릭 가능하고 짙은 브라우즈가 가능합니다 JavaScript 객체의 내용. %s 기록을 위해 보여졌습니다.

또한 이것도 멋지다 :

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

Java와 같은 스택을 new Error() 호출 (포함 파일 및 줄 번호로가는 경로!).

둘 다 %o 그리고 new Error().stack Chrome과 Firefox에서 구입할 수 있습니다!

Firefox 사용의 스택 추적도 :

console.trace();

처럼 https://developer.mozilla.org/en-us/docs/web/api/console 말한다.

행복한 해킹!

업데이트: 일부 도서관은 console 그들 자신의 목적을 위해 반대. 원래 브라우저를 복원합니다 console 라이브러리로드 후 사용 :

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

스택 오버 플로우 질문을 참조하십시오 Console.log () 복원.

빠른 경고 만 - 모든 콘솔을 제거하지 않고 인터넷 익스플로러에서 테스트하려면 사용해야합니다. 소방대 라이트 또는 특히 친근한 오류가 발생하지 않을 것입니다.

(또는 거짓을 반환하는 나만의 콘솔을 만듭니다.)

다음은 콘솔을 사용할 수 있는지 확인하는 짧은 스크립트입니다. 그렇지 않은 경우로드하려고합니다 개똥 벌레 Firebug를 사용할 수 없으면 Firebug Lite를로드합니다. 이제 사용할 수 있습니다 console.log 모든 브라우저에서. 즐기다!

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.
}

에 추가 Delan Azabani의 대답, 나는 내 공유하고 싶다 console.js, 그리고 나는 같은 목적으로 사용합니다. 기능 이름을 사용하여 Noop 콘솔을 만듭니다. 제 생각에는이 작업을 수행하는 매우 편리한 방법입니다. 인터넷 익스플로러를 관리했습니다. console.log 기능이지만 아니요 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() {};
  }
}

또는이 기능을 사용하십시오.

function log(message){
    if (typeof console == "object") {
        console.log(message);
    }
}

여기 내 콘솔 래퍼 클래스가 있습니다. 그것은 삶을 더 쉽게 만들 수 있도록 범위 출력을 제공합니다. 사용에 유의하십시오 localConsole.debug.call() ~하도록 하다 localConsole.debug 호출 클래스의 범위에서 실행되며, 그에 대한 액세스를 제공합니다. 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();

이것은 그런 것과 같은 출력을 제공합니다 개똥 벌레:

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

또는 크롬 :

In scope of someClass.someFunc(), obj:
Object
cat: "hat"
dr: "zeus"
__proto__: Object

개인적으로 나는 이것을 사용하는데, 이것은 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){}
}

요점은 적어도 고집하는 것 외에 다른 로깅을 실천하는 것이 좋은 생각입니다. console.log() JavaScript 코드에 바로 잊어 버리고 제작 사이트에 있으면 해당 페이지의 모든 JavaScript 코드를 잠재적으로 분해 할 수 있기 때문입니다.

당신은 사용할 수 있습니다 console.log() 어떤 프로그래밍 소프트웨어 편집기에 디버깅 된 코드가있는 경우, 출력이 나에게 가장 적합한 편집기 (Google Chrome) 일 가능성이 높습니다. 그냥 누르십시오 F12 콘솔 탭을 누릅니다. 결과를 볼 수 있습니다. 행복한 코딩. :)

개발자가 콘솔에서 확인하는 데 많은 문제가있었습니다. () 문장. 그리고 나는 환상적인 개선에도 불구하고 인터넷 익스플로러를 디버깅하는 것을 좋아하지 않습니다. 인터넷 익스플로러 10 그리고 Visual Studio 2012, 등.

그래서 콘솔 객체 자체를 재정의했습니다 ... localhost에서 콘솔 문 만 허용하는 __localhost 플래그를 추가했습니다. 또한 Console. () 함수를 Internet Explorer에 추가했습니다 (대신 ALERT ()를 표시).

// 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));
            }
        }
    };
})();

예제 사용 :

    console.log("hello");

크롬/파이어 폭스 :

    prints hello in the console window.

인터넷 익스플로러:

    displays an alert with 'hello'.

코드를 자세히 살펴 보는 사람들은 console.examine () 함수를 발견하게됩니다. 나는 몇 년 전에 제품 주변의 특정 영역에 디버그 코드를 남겨 두어 문제 해결에 도움이 될 수 있도록 만들었습니다. QA/고객 문제. 예를 들어, 나는 다음 줄을 릴리스 코드로 남겨 둘 것입니다.

    function doSomething(arg1) {
        // ...
        console.examine("someLabel", arg1);
        // ...
    }

그런 다음 공개 된 제품에서 다음을 콘솔에 입력하십시오 (또는 'JavaScript :'로 접두사 주소 막대) : :

    top.__examine_someLabel = true;

그런 다음 기록 된 모든 Console.examine () 문을 볼 수 있습니다. 여러 번 환상적인 도움이되었습니다.

단순한 인터넷 익스플로러 7 그리고 아래 틈 메우는 나무 다른 브라우저의 라인 번호를 보존합니다.

/* Console shim */
(function () {
    var f = function () {};
    if (!window.console) {
        window.console = {
            log:f, info:f, warn:f, debug:f, error:f
        };
    }
}());
console.debug("");

이 방법을 사용하면 콘솔의 밝은 파란색으로 텍스트를 인쇄합니다.

enter image description here

Delan과 Andru의 아이디어에 대한 추가 개선 (이 답변이 편집 된 버전 인 이유); Console.log가 존재할 가능성이 높습니다. 다른 기능은 그렇지 않을 수 있으므로 Console.log와 동일한 함수에 대한 기본 맵이 있어야합니다 ....

존재하지 않으면 콘솔 기능을 만드는 스크립트를 작성할 수 있습니다.

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

그런 다음 다음 중 하나를 사용하십시오.

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

이 기능은 다른 유형의 항목 (로그, 정보, 오류 또는 경고를 기반으로 필터링 할 수 있음)을 기록하며 콘솔을 사용할 수없는 경우 오류가 발생하지 않습니다. 이러한 기능은 Firebug 및 Chrome 콘솔에서 작동합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top