IE9 中,開啟開發者工具(F12)時 console 存在,代碼正常運行;關閉開發者工具後,console 變為 undefined,任何 console.log() 均拋出「'console' 未定義」錯誤,導致腳本中斷。
IE9 將 console 物件綁定於開發者工具的生命週期。工具關閉時,window.console 被移除,而非像現代瀏覽器那樣始終存在且方法為空函數。
// 立即執行函數,避免污染全局
(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() {};
});
})();
terser / uglifyjs 開啟 drop_console: true。loglevel、pino(Node)、bowser 等可配置級別、輸出目標的庫。/*@cc_on ... @*/ 僅在 IE 執行 Polyfill,避免污染其他瀏覽器。<!--[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 關閉開發者工具後腳本崩潰問題,保障生產環境穩定運行。