【笨問題】IE9的「console未被定義」錯誤
5 |
一直以來,有個鬼現象纏著我揮之不去,console.log常因不明原因在IE9出現SCRIPT5009: 'console' is undefined (console未被定義) 錯誤!
我當然知道IE從IE8+才支援console物件,但如上圖所示,網頁明明是IE9標準模式,為什麼IE9卻說console物件不存在? 但進行偵錯,console.log()卻又正常!
笨了好久,今天才解開謎團:
IE8/IE9要先按F12開啟IE Dev Tools才能存取console物件啦! 笨蛋!
參考來源: http://msdn.microsoft.com/en-us/library/ie/gg589530(v=vs.85).aspx
… You use the console object to send a message to the console from your code. Using the console instead of "window.alert()" when testing code is less obtrusive and doesn't stop you with a modal dialog box. This object provides a number of forms so that you can distinguish between informational messages and error messages if you want. When you use the console object, make sure that the F12 tools are open. To avoid executing needless code, use the following feature test …
所以,如果使用環境包含IE8/9,請養成良好習慣,用if (window.console) { ... }包住console.log()動作,切忌把IE8/9想成Chrome/Firefox,以為永遠有window.console可用!
PS: 終於,IE10改邪歸正向Chrome/Firefox看齊,console不再像段譽的六脈神劍時有時無。但只要IE8/9還在一天,console檢查還是不能少。
Comments
# by 西門貓
我也被這問題搞過T_T
# by Anlun
最近幫人Debug程式,剛看到這個錯誤,還不太敢相信,後來移除掉console才正常,原來真的不支援。
# by YYYCCC
20202的我還是遇到這問題了QQ 不要問我為甚麼還有IE8
# by Junyu
2020/12 的我也遇到了QQ IE8依然活著
# by iryn
2021/08 ie 9 still alive