どちらのソリューションをお勧めしますか、2番目の方が簡単です(コードが少ない)が、それを使用すると欠点がありますか?
First:(グローバルデバッグフラグを設定)
// the first line of code
var debug = true;
try {
console.log
} catch(e) {
if(e) {
debug=false;
}
};
// Then later in the code
if(debug) {
console.log(something);
}
2番目: console.logを上書き
try {
console.log
} catch(e) {
if (e) {
console.log = function() {}
}
};
// And all you need to do in the code is
console.log(something);
どちらでもありませんが、2番目のバリエーションです。 try...catch
をなくして、コンソールオブジェクトの存在を適切に確認します。
if (typeof console == "undefined") {
window.console = {
log: function () {}
};
}
console.log("whatever");
または、コーヒースクリプトで:
window.console ?=
log:-> #patch so console.log() never causes error even in IE.
編集:アンディの答え は、以下に掲載したクイックハックよりもはるかにエレガントです。
私は通常、このアプローチを使用しています...
// prevent console errors on browsers without firebug
if (!window.console) {
window.console = {};
window.console.log = function(){};
}
私は過去に同様のバグに直面したことがあり、以下のコードでそれを克服しました:
if(!window.console) {
var console = {
log : function(){},
warn : function(){},
error : function(){},
time : function(){},
timeEnd : function(){}
}
}
私は他の回答と同様にこの投稿に出くわしました:
http://jennyandlih.com/resolved-logging-firebug-console-breaks-ie
以下はあなたが探しているものを実現します:
window.console && console.log('foo');
window.console = window.console || {};
window.console.log = window.console.log || function() {};