啟用 Firebug 面板之後,頁面會多出一個 window.console 物件,並在 window.console.firebug 上保存當前 Firebug 的版本號;關閉面板後則恢復正常。因此只要判斷這個屬性是否存在,就能知道 Firebug 有沒有開著。
Boolean(window.console && window.console.firebug)
這段偵測實作也點出了一個常見痛點:頁面裡寫了 console.log(),但使用者沒開 Firebug(或用的是 IE 舊版),console 物件不存在,腳本就直接報錯中斷。
解法是在腳本最前面手工建立一個空的 console 物件,把常用的方法都補成空函式:
if (!window.console) {
// 未安裝 Firebug 時忽略相關呼叫
(function (m, i) {
window.console = {};
while (i--) {
window.console[m[i]] = function () {};
}
}('log debug info warn exception assert dir dirxml trace group groupEnd ' +
'groupCollapsed time timeEnd profile profileEnd count clear table error ' +
'notifyFirebug'.split(' '), 22));
}
這樣一來,在 IE 下能正常預覽頁面,在 Firefox、Chrome、Safari 中也能正常輸出除錯資訊。
Firebug 早已停止維護,其功能被各瀏覽器內建的開發者工具取代,而 所有現代瀏覽器都原生提供 window.console,因此上面那段 polyfill 在今天已無必要。
若你只是想「在非除錯環境中靜默掉 log」,比較好的做法有兩種:
drop_console 選項,在打包時把 console 呼叫整批清掉,正式環境完全不含這些程式碼。const log = DEBUG ? console.log.bind(console) : function(){} 這類寫法統一控制,同時能加上層級、時間戳記與來源標記。直接覆寫 console 的做法會讓真正需要除錯的人看不到任何輸出,排查線上問題時反而更棘手,不建議採用。