2012-11-11

console.log fallback

上次遇到 console.log 在 IE 上的問題, stackoverflow  上有不錯的解法。
「console.log is only available after you have opened the Developer Tools」只能說花熱發...

練習打包成小工具 console_log_fallback.js
(function(){
  'use strict';
  var _scripts = document.getElementsByTagName('script');
  var _script = _scripts[_scripts.length-1];
  var _url = _script.src;
  var _qi = _url ? _url.indexOf('?') : -1;
  var alertStead = false;
  var i, param, params = _url.substr(_qi + 1).split('&');
  for (i = 0; i < params.length; i++) {
      param = params[i].split('=');
      if (param[0]=='alert' && parseInt(param[1])) {
          alertStead = true;
      }
  }

  if (typeof console === "undefined" || typeof console.log === "undefined") {
    console = {};
    if (alertStead) {
      console.log = function(msg) {
        alert(msg);
      };
    } else {
      console.log = function() {};
    }
  }
})();
使用以下方式時, 在 IE 可以用 alert 來替代 console.log 除錯:
<script src="console_log_fallback.js?alert=1" type="text/javascript"></script>

2 則留言:

Shinder 提到...

也可以用最簡單的方式避開, 尤其 IE8
(function(){
if (typeof console === "undefined" || typeof console.log === "undefined") {
console = {};
console.log = function() {};
}
})();

Shinder 提到...

window.console ? false : (window.console={});
window.console.log ? false : (window.console.log=function(){});

FB 留言