我使用Firebug,并有一些语句像:
console.log("...");
在我的页面上。在IE8(可能是更早的版本),我得到脚本错误说“控制台”是未定义的。我试着把这个放在我页面的顶部:
<script type="text/javascript">
if (!console) console = {log: function() {}};
</script>
我还是会得到错误。有办法消除错误吗?
我使用Firebug,并有一些语句像:
console.log("...");
在我的页面上。在IE8(可能是更早的版本),我得到脚本错误说“控制台”是未定义的。我试着把这个放在我页面的顶部:
<script type="text/javascript">
if (!console) console = {log: function() {}};
</script>
我还是会得到错误。有办法消除错误吗?
当前回答
You can use the below to give an extra degree of insurance that you've got all bases covered. Using typeof first will avoid any undefined errors. Using === will also ensure that the name of the type is actually the string "undefined". Finally, you'll want to add a parameter to the function signature (I chose logMsg arbitrarily) to ensure consistency, since you do pass whatever you want printed to the console to the log function. This also keep you intellisense accurate and avoids any warnings/errors in your JS aware IDE.
if(!window.console || typeof console === "undefined") {
var console = { log: function (logMsg) { } };
}
其他回答
在IE9中,如果控制台未打开,以下代码:
alert(typeof console);
会显示“对象”,但这个代码
alert(typeof console.log);
将抛出TypeError异常,但不返回未定义的值;
因此,保证版本的代码将类似于:
try {
if (window.console && window.console.log) {
my_console_log = window.console.log;
}
} catch (e) {
my_console_log = function() {};
}
对于IE8或控制台支持仅限于console.log(没有调试,跟踪,…),您可以执行以下操作:
如果console或console.log未定义:为 控制台函数(跟踪,调试,日志,…) 窗口。控制台= { Debug: function(){},…}; 否则,如果console.log被定义(IE8)和console.debug(任何其他)没有定义:重定向所有日志功能到console.log,这允许保留这些日志! 窗口。控制台= { 调试:window.console.log,…};
不确定在各种IE版本中的assert支持,但欢迎任何建议。也在这里发布了这个答案:我如何在Internet Explorer中使用控制台登录?
有时控制台可以在IE8/9中工作,但在其他时候会失败。这种不稳定的行为取决于你是否打开了开发工具,并在stackoverflow问题中描述了IE9是否支持console.log,这是一个真实的函数吗?
在TypeScript中控制台的存根:
if (!window.console) {
console = {
assert: () => undefined,
clear: () => undefined,
count: () => undefined,
debug: () => undefined,
dir: () => undefined,
dirxml: () => undefined,
error: () => undefined,
group: () => undefined,
groupCollapsed: () => undefined,
groupEnd: () => undefined,
info: () => undefined,
log: () => undefined,
msIsIndependentlyComposed: (e: Element) => false,
profile: () => undefined,
profileEnd: () => undefined,
select: () => undefined,
time: () => undefined,
timeEnd: () => undefined,
trace: () => undefined,
warn: () => undefined,
}
};
在IE9的子窗口中运行console.log时遇到类似问题,由window创建。打开功能。
在这种情况下,控制台似乎只在父窗口中定义,在刷新子窗口之前没有定义。同样适用于子窗口的子窗口。
我处理这个问题通过包装log在下一个函数(下面是模块的片段)
getConsole: function()
{
if (typeof console !== 'undefined') return console;
var searchDepthMax = 5,
searchDepth = 0,
context = window.opener;
while (!!context && searchDepth < searchDepthMax)
{
if (typeof context.console !== 'undefined') return context.console;
context = context.opener;
searchDepth++;
}
return null;
},
log: function(message){
var _console = this.getConsole();
if (!!_console) _console.log(message);
}