Internet Explorer 9在哪些情况下定义window.console.log ?
即使定义了window.console.log, window.console.log.apply和window.console.log.call也是未定义的。为什么会这样?
[IE8的相关问题:在IE8中console.log发生了什么?]
Internet Explorer 9在哪些情况下定义window.console.log ?
即使定义了window.console.log, window.console.log.apply和window.console.log.call也是未定义的。为什么会这样?
[IE8的相关问题:在IE8中console.log发生了什么?]
当前回答
我知道这是一个非常古老的问题,但我认为这为如何处理主机问题提供了一个有价值的选择。在任何对控制台的调用之前放置以下代码。*(你的第一个剧本)。
// Avoid `console` errors in browsers that lack a console.
(function() {
var method;
var noop = function () {};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
参考: https://github.com/h5bp/html5-boilerplate/blob/v5.0.0/dist/js/plugins.js
其他回答
console.log仅在控制台打开时定义。如果你想在你的代码中检查它,请确保在window属性中检查它
if (window.console)
console.log(msg)
这会在IE9中抛出一个异常,并且不能正常工作。不要这样做
if (console)
console.log(msg)
在阅读了Marc climate上面的评论后,我现在改变了我的多功能跨浏览器console.log函数,如下所示:
function log()
{
"use strict";
if (typeof(console) !== "undefined" && console.log !== undefined)
{
try
{
console.log.apply(console, arguments);
}
catch (e)
{
var log = Function.prototype.bind.call(console.log, console);
log.apply(console, arguments);
}
}
}
我想说的是,如果你在所有版本的Windows上关闭开发者工具使用console.log, IE9不会引发这个错误。XP系统有,但Windows 7系统没有。 所以如果你放弃了对WinXP的支持,你可以直接使用console.log。
如何……
console = { log : function(text) { alert(text); } }
console.log问题的一个简单解决方案是在JS代码的开头定义以下内容:
if (!window.console) window.console = {};
if (!window.console.log) window.console.log = function () { };
这在所有浏览器中都适用。这将在调试器未激活时为console.log创建一个虚拟函数。当调试器处于活动状态时,将定义console.log方法并正常执行。