Programming

Internet Explorer에서 'console'은 정의되지 않은 오류입니다.

procodes 2020. 2. 26. 22:47
반응형

Internet Explorer에서 'console'은 정의되지 않은 오류입니다.


Firebug를 사용하고 있으며 다음과 같은 문장이 있습니다.

console.log("...");

내 페이지에서. IE8 (아마도 이전 버전)에서도 'console'이 정의되지 않았다는 스크립트 오류가 발생합니다. 내 페이지 맨 위에 이것을 넣으려고했습니다.

<script type="text/javascript">
    if (!console) console = {log: function() {}};
</script>

여전히 오류가 발생합니다. 오류를 제거하는 방법이 있습니까?


시험

if (!window.console) console = ...

정의되지 않은 변수는 직접 참조 할 수 없습니다. 그러나 모든 전역 변수는 window브라우저의 경우 전역 컨텍스트와 동일한 이름의 속성이므로 정의되지 않은 속성에 액세스하는 것이 좋습니다.

또는 if (typeof console === 'undefined') console = ...매직 변수를 피하려면 @Tim Down의 답변을window 참조하십시오 .


콘솔을 사용하기 전에 JavaScript 맨 위에 다음을 붙여 넣습니다.

/**
 * Protect window.console method calls, e.g. console is not defined on IE
 * unless dev tools are open, and IE doesn't define console.debug
 * 
 * Chrome 41.0.2272.118: debug,error,info,log,warn,dir,dirxml,table,trace,assert,count,markTimeline,profile,profileEnd,time,timeEnd,timeStamp,timeline,timelineEnd,group,groupCollapsed,groupEnd,clear
 * Firefox 37.0.1: log,info,warn,error,exception,debug,table,trace,dir,group,groupCollapsed,groupEnd,time,timeEnd,profile,profileEnd,assert,count
 * Internet Explorer 11: select,log,info,warn,error,debug,assert,time,timeEnd,timeStamp,group,groupCollapsed,groupEnd,trace,clear,dir,dirxml,count,countReset,cd
 * Safari 6.2.4: debug,error,log,info,warn,clear,dir,dirxml,table,trace,assert,count,profile,profileEnd,time,timeEnd,timeStamp,group,groupCollapsed,groupEnd
 * Opera 28.0.1750.48: debug,error,info,log,warn,dir,dirxml,table,trace,assert,count,markTimeline,profile,profileEnd,time,timeEnd,timeStamp,timeline,timelineEnd,group,groupCollapsed,groupEnd,clear
 */
(function() {
  // Union of Chrome, Firefox, IE, Opera, and Safari console methods
  var methods = ["assert", "cd", "clear", "count", "countReset",
    "debug", "dir", "dirxml", "error", "exception", "group", "groupCollapsed",
    "groupEnd", "info", "log", "markTimeline", "profile", "profileEnd",
    "select", "table", "time", "timeEnd", "timeStamp", "timeline",
    "timelineEnd", "trace", "warn"];
  var length = methods.length;
  var console = (window.console = window.console || {});
  var method;
  var noop = function() {};
  while (length--) {
    method = methods[length];
    // define undefined methods as noops to prevent errors
    if (!console[method])
      console[method] = noop;
  }
})();

함수 클로저 래퍼는 변수를 정의하지 않도록 변수의 범위를 지정하는 것입니다. 이것은 정의되지 않은 메소드 console와 정의되지 않은 console.debug메소드 및 기타 누락 된 메소드를 방지합니다.

편집 : HTML5 보일러 플레이트 는 js / plugins.js 파일에서 유사한 코드를 사용 한다는 것을 알았 습니다. 아마도 최신 상태로 유지되는 솔루션을 찾고 있다면.


다른 대안은 typeof연산자입니다.

if (typeof console == "undefined") {
    this.console = {log: function() {}};
}

또 다른 대안은 내 자신의 log4javascript 와 같은 로깅 라이브러리를 사용하는 것 입니다.


보다 강력한 솔루션을 위해 다음 코드를 사용하십시오 (twitter의 소스 코드에서 가져옴).

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

내 스크립트에서 나는 속기를 사용합니다.

window.console && console.log(...) // only log if the function exists

또는 모든 console.log 줄을 편집 할 수 없거나 실행 가능하지 않은 경우 가짜 콘솔을 만듭니다.

// check to see if console exists. If not, create an empty object for it,
// then create and empty logging function which does nothing. 
//
// REMEMBER: put this before any other console.log calls
!window.console && (window.console = {} && window.console.log = function () {});

당신이 사용할 수있는 console.log()당신이있는 경우에 Developer ToolsIE8 열고 또한 당신이 사용할 수에 Console스크립트 탭에서 텍스트 상자를.


if (typeof console == "undefined") {
  this.console = {
    log: function() {},
    info: function() {},
    error: function() {},
    warn: function() {}
  };
}

두 개의 이전 답변을 기반으로

에 대한 문서

다음은 문제에 대한 최선의 구현입니다. 실제로 존재하는 console.log가 있으면 console.log를 통해 존재하지 않는 메소드의 격차를 메 웁니다.

예를 들어 IE6 ​​/ 7의 경우 로깅을 경고로 대체 할 수 있습니다 (멍청하지만 작동합니다). 그리고 아래 괴물을 포함시킬 수 있습니다 (콘솔 .js라고 부릅니다). 최소화 기가 문제를 해결할 수 있음] :

<!--[if lte IE 7]>
<SCRIPT LANGUAGE="javascript">
    (window.console = window.console || {}).log = function() { return window.alert.apply(window, arguments); };
</SCRIPT>
<![endif]-->
<script type="text/javascript" src="console.js"></script>

및 console.js :

    /**
     * Protect window.console method calls, e.g. console is not defined on IE
     * unless dev tools are open, and IE doesn't define console.debug
     */
    (function() {
        var console = (window.console = window.console || {});
        var noop = function () {};
        var log = console.log || noop;
        var start = function(name) { return function(param) { log("Start " + name + ": " + param); } };
        var end = function(name) { return function(param) { log("End " + name + ": " + param); } };

        var methods = {
            // Internet Explorer (IE 10): http://msdn.microsoft.com/en-us/library/ie/hh772169(v=vs.85).aspx#methods
            // assert(test, message, optionalParams), clear(), count(countTitle), debug(message, optionalParams), dir(value, optionalParams), dirxml(value), error(message, optionalParams), group(groupTitle), groupCollapsed(groupTitle), groupEnd([groupTitle]), info(message, optionalParams), log(message, optionalParams), msIsIndependentlyComposed(oElementNode), profile(reportName), profileEnd(), time(timerName), timeEnd(timerName), trace(), warn(message, optionalParams)
            // "assert", "clear", "count", "debug", "dir", "dirxml", "error", "group", "groupCollapsed", "groupEnd", "info", "log", "msIsIndependentlyComposed", "profile", "profileEnd", "time", "timeEnd", "trace", "warn"

            // Safari (2012. 07. 23.): https://developer.apple.com/library/safari/#documentation/AppleApplications/Conceptual/Safari_Developer_Guide/DebuggingYourWebsite/DebuggingYourWebsite.html#//apple_ref/doc/uid/TP40007874-CH8-SW20
            // assert(expression, message-object), count([title]), debug([message-object]), dir(object), dirxml(node), error(message-object), group(message-object), groupEnd(), info(message-object), log(message-object), profile([title]), profileEnd([title]), time(name), markTimeline("string"), trace(), warn(message-object)
            // "assert", "count", "debug", "dir", "dirxml", "error", "group", "groupEnd", "info", "log", "profile", "profileEnd", "time", "markTimeline", "trace", "warn"

            // Firefox (2013. 05. 20.): https://developer.mozilla.org/en-US/docs/Web/API/console
            // debug(obj1 [, obj2, ..., objN]), debug(msg [, subst1, ..., substN]), dir(object), error(obj1 [, obj2, ..., objN]), error(msg [, subst1, ..., substN]), group(), groupCollapsed(), groupEnd(), info(obj1 [, obj2, ..., objN]), info(msg [, subst1, ..., substN]), log(obj1 [, obj2, ..., objN]), log(msg [, subst1, ..., substN]), time(timerName), timeEnd(timerName), trace(), warn(obj1 [, obj2, ..., objN]), warn(msg [, subst1, ..., substN])
            // "debug", "dir", "error", "group", "groupCollapsed", "groupEnd", "info", "log", "time", "timeEnd", "trace", "warn"

            // Chrome (2013. 01. 25.): https://developers.google.com/chrome-developer-tools/docs/console-api
            // assert(expression, object), clear(), count(label), debug(object [, object, ...]), dir(object), dirxml(object), error(object [, object, ...]), group(object[, object, ...]), groupCollapsed(object[, object, ...]), groupEnd(), info(object [, object, ...]), log(object [, object, ...]), profile([label]), profileEnd(), time(label), timeEnd(label), timeStamp([label]), trace(), warn(object [, object, ...])
            // "assert", "clear", "count", "debug", "dir", "dirxml", "error", "group", "groupCollapsed", "groupEnd", "info", "log", "profile", "profileEnd", "time", "timeEnd", "timeStamp", "trace", "warn"
            // Chrome (2012. 10. 04.): https://developers.google.com/web-toolkit/speedtracer/logging-api
            // markTimeline(String)
            // "markTimeline"

            assert: noop, clear: noop, trace: noop, count: noop, timeStamp: noop, msIsIndependentlyComposed: noop,
            debug: log, info: log, log: log, warn: log, error: log,
            dir: log, dirxml: log, markTimeline: log,
            group: start('group'), groupCollapsed: start('groupCollapsed'), groupEnd: end('group'),
            profile: start('profile'), profileEnd: end('profile'),
            time: start('time'), timeEnd: end('time')
        };

        for (var method in methods) {
            if ( methods.hasOwnProperty(method) && !(method in console) ) { // define undefined methods as best-effort methods
                console[method] = methods[method];
            }
        }
    })();

IE9에서 콘솔이 열리지 않으면이 코드는 다음과 같습니다.

alert(typeof console);

"object"가 표시되지만이 코드

alert(typeof console.log);

TypeError 예외가 발생하지만 정의되지 않은 값을 반환하지 않습니다.

따라서 보장 된 코드 버전은 다음과 유사합니다.

try {
    if (window.console && window.console.log) {
        my_console_log = window.console.log;
    }
} catch (e) {
    my_console_log = function() {};
}

내 코드에는 console.log 만 사용하고 있습니다. 그래서 저는 아주 짧은 2 라이너를 포함합니다

var console = console || {};
console.log = console.log || function(){};

OP는 IE와 함께 Firebug를 사용하고 있으므로 Firebug Lite 라고 가정합니다 . 디버거 창이 열릴 때 콘솔이 IE에서 정의되면 펑키 한 상황이지만 Firebug가 이미 실행 중이면 어떻게됩니까? 확실하지 않지만 "firebugx.js"메소드는이 상황에서 테스트하는 좋은 방법 일 수 있습니다.

출처:

https://code.google.com/p/fbug/source/browse/branches/firebug1.2/lite/firebugx.js?r=187

    if (!window.console || !console.firebug) {
        var names = [
            "log", "debug", "info", "warn", "error", "assert",
            "dir","dirxml","group","groupEnd","time","timeEnd",
            "count","trace","profile","profileEnd"
        ];
        window.console = {};
        for (var i = 0; i < names.length; ++i)
            window.console[names[i]] = function() {}
    }

(2014 년 12 월 링크 업데이트)


fauxconsole을 사용 하고 있습니다 . css를 약간 수정하여 멋지게 보이지만 잘 작동합니다.


IE에서 디버깅하려면이 log4를 확인하십시오.


console.log (디버그, 추적 등)로 제한된 IE8 또는 콘솔 지원의 경우 다음을 수행 할 수 있습니다.

  • console OR console.log가 정의되지 않은 경우 : 콘솔 함수 (추적, 디버그, 로그 등)에 대한 더미 함수를 작성하십시오.

    window.console = { debug : function() {}, ...};

  • console.log가 정의되어 있고 (IE8) console.debug (기타)가 정의되어 있지 않은 경우 : 모든 로깅 기능을 console.log로 리디렉션하면 로그를 유지할 수 있습니다!

    window.console = { debug : window.console.log, ...};

다양한 IE 버전의 주장 지원에 대해서는 확실하지 않지만 제안은 환영합니다. 또한 여기이 답변을 게시 : 어떻게 Internet Explorer에서 콘솔 로깅을 사용할 수 있습니까?


console = console || { 
    debug: function(){}, 
    log: function(){}
    ...
}

TypeScript에서 콘솔 스텁 :

if (!window.console) {
console = {
    assert: () => { },
    clear: () => { },
    count: () => { },
    debug: () => { },
    dir: () => { },
    dirxml: () => { },
    error: () => { },
    group: () => { },
    groupCollapsed: () => { },
    groupEnd: () => { },
    info: () => { },
    log: () => { },
    msIsIndependentlyComposed: (e: Element) => false,
    profile: () => { },
    profileEnd: () => { },
    select: () => { },
    time: () => { },
    timeEnd: () => { },
    trace: () => { },
    warn: () => { },
    }
};

아래를 사용하여 모든 기지에 적용되는 추가 보험을 제공 할 수 있습니다. typeof먼저 사용하면 undefined오류 가 발생하지 않습니다. 를 사용 ===하면 유형의 이름이 실제로 "정의되지 않은"문자열인지 확인합니다. 마지막으로 logMsg콘솔에 인쇄하려는 모든 것을 로그 함수로 전달하기 때문에 일관성을 유지하기 위해 함수 서명에 매개 변수를 추가하려고합니다 ( 임의로 선택했습니다 ). 또한 인텔리전스를 정확하게 유지하고 JS 인식 IDE의 경고 / 오류를 방지합니다.

if(!window.console || typeof console === "undefined") {
  var console = { log: function (logMsg) { } };
}

때때로 콘솔은 IE8 / 9에서 작동하지만 다른 시간에는 실패합니다. 이 잘못된 동작은 개발자 도구가 열려 있는지 여부에 따라 달라지며 stackoverflow 질문에 설명되어 있습니다 . IE9는 console.log를 지원합니까? 이것이 실제 기능입니까?


IE.9의 자식 창에서 console.log를 실행하는 비슷한 문제가 window.open 함수로 생성되었습니다.

이 경우 콘솔은 부모 창에서만 정의되고 새로 고칠 때까지 자식 창에서는 정의되지 않은 것 같습니다. 자식 창의 자식에도 동일하게 적용됩니다.

다음 함수에 로그를 래핑 하여이 문제를 처리합니다 (아래는 모듈 조각입니다).

getConsole: function()
    {
        if (typeof console !== 'undefined') return console;

        var searchDepthMax = 5,
            searchDepth = 0,
            context = window.opener;

        while (!!context && searchDepth < searchDepthMax)
        {
            if (typeof context.console !== 'undefined') return context.console;

            context = context.opener;
            searchDepth++;
        }

        return null;
    },
    log: function(message){
        var _console = this.getConsole();
        if (!!_console) _console.log(message);
    }

이 문제에 대해 너무 많은 문제를 겪은 후에 (개발자 콘솔을 열면 오류가 더 이상 발생하지 않으므로 오류를 디버깅하기가 어렵습니다!)이 문제를 다시는 신경 쓰지 않기 위해 과도한 코드를 작성하기로 결정했습니다.

if (typeof window.console === "undefined")
    window.console = {};

if (typeof window.console.debug === "undefined")
    window.console.debug= function() {};

if (typeof window.console.log === "undefined")
    window.console.log= function() {};

if (typeof window.console.error === "undefined")
    window.console.error= function() {alert("error");};

if (typeof window.console.time === "undefined")
    window.console.time= function() {};

if (typeof window.console.trace === "undefined")
    window.console.trace= function() {};

if (typeof window.console.info === "undefined")
    window.console.info= function() {};

if (typeof window.console.timeEnd === "undefined")
    window.console.timeEnd= function() {};

if (typeof window.console.group === "undefined")
    window.console.group= function() {};

if (typeof window.console.groupEnd === "undefined")
    window.console.groupEnd= function() {};

if (typeof window.console.groupCollapsed === "undefined")
    window.console.groupCollapsed= function() {};

if (typeof window.console.dir === "undefined")
    window.console.dir= function() {};

if (typeof window.console.warn === "undefined")
    window.console.warn= function() {};

Personaly 나는 console.log와 console.error 만 사용하지만이 코드는 Mozzila Developer Network에 표시된 다른 모든 기능을 처리합니다 : https://developer.mozilla.org/en-US/docs/Web/API/console . 페이지 상단에 해당 코드를 입력하면이 작업이 끝없이 완료됩니다.


Firefox에서는 직접 console.log (...)를 사용할 수 있지만 IE에서는 사용할 수 없습니다. IE에서는 window.console을 사용해야합니다.

참고 URL : https://stackoverflow.com/questions/3326650/console-is-undefined-error-for-internet-explorer



반응형