萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

IE9 控制台關閉後 console 未定義錯誤的根因與 Polyfill 方案

現象復現

IE9 中,開啟開發者工具(F12)時 console 存在,代碼正常運行;關閉開發者工具後,console 變為 undefined,任何 console.log() 均拋出「'console' 未定義」錯誤,導致腳本中斷。

根本原因

IE9 將 console 物件綁定於開發者工具的生命週期。工具關閉時,window.console 被移除,而非像現代瀏覽器那樣始終存在且方法為空函數。

通用 Polyfill 方案(置於所有腳本之前)

// 立即執行函數,避免污染全局
(function() {
    if (!window.console) {
        window.console = {};
    }
    var methods = [
        'log', 'warn', 'debug', 'info', 'error',
        'time', 'timeEnd', 'timeLog',
        'dir', 'dirxml',
        'table', 'trace',
        'assert', 'count', 'countReset',
        'group', 'groupEnd', 'groupCollapsed',
        'clear', 'profile', 'profileEnd',
        'memory' // 非標準,僅 Chrome
    ];
    var noop = function() {};
    methods.forEach(function(method) {
        if (!window.console[method]) {
            window.console[method] = noop;
        }
    });
    // 兼容 console.log.apply 等調用
    if (!console.log.apply) {
        console.log.apply = function() { noop.apply(console, arguments); };
    }
})();

進階:保留開發環境輸出,生產環境靜默

(function() {
    if (window.console && window.console.log) return; // 已有完整 console
    var isDev = location.hostname === 'localhost' || location.search.indexOf('debug') > -1;
    var methods = ['log','warn','error','info','debug','time','timeEnd'];
    window.console = {};
    methods.forEach(function(m) {
        window.console[m] = isDev ? function() {
            // 開發環境:嘗試轉發給真實 console(若開啟了開發者工具)
            try { (window.console[m] || Function.prototype).apply(console, arguments); } catch(e) {}
        } : function() {};
    });
})();

最佳實踐建議

  1. 生產代碼移除所有 console.*:構建流程中用 terser / uglifyjs 開啟 drop_console: true。
  2. 開發環境保留:Source Map 映射回源碼行號。
  3. 日誌庫替代:使用 loglevel、pino(Node)、bowser 等可配置級別、輸出目標的庫。
  4. 條件編譯:IE 專用註釋 /*@cc_on ... @*/ 僅在 IE 執行 Polyfill,避免污染其他瀏覽器。

條件編譯寫法(僅 IE9-10 執行)

<!--[if lte IE 9]>
<script>
(function() {
    if (!window.console) window.console = {};
    var m = ['log','warn','error','info','debug','time','timeEnd','dir','trace','assert'];
    for (var i=0; i<m.length; i++) if (!console[m[i]]) console[m[i]] = function() {};
})();
</script>
<![endif]-->

徹底解決 IE9 關閉開發者工具後腳本崩潰問題,保障生產環境穩定運行。

copyright © 萬盛學電腦網 all rights reserved