mlo*_*ran 206 javascript logging internet-explorer-9
在window.console.logInternet Explorer 9中定义了哪些情况?
即使window.console.log被定义,window.console.log.apply并且window.console.log.call是不确定的.为什么是这样?
[IE8的相关问题:IE8 中的console.log发生了什么变化?]
And*_*y E 297
在Internet Explorer 9(和8)中,console只有在为特定选项卡打开开发人员工具时才会显示该对象.如果隐藏该选项卡的开发人员工具窗口,则console对于您导航到的每个页面,对象将保持公开状态.如果打开新选项卡,则还必须打开该选项卡的开发人员工具,以便console公开对象.
该console对象不是任何标准的一部分,是文档对象模型的扩展.与其他DOM对象一样,它被认为是一个宿主对象,不需要像本机ECMAScript函数和对象那样继承Object,也不需要继承它的方法Function.这是原因apply,call并且在这些方法上未定义.在IE 9中,大多数DOM对象都得到了改进,可以从本机ECMAScript类型继承.由于开发人员工具被认为是IE的扩展(虽然是内置扩展),但他们显然没有得到与其他DOM相同的改进.
对于它的价值,您仍然可以在Function.prototype方法上使用一些console方法,但有一点bind()魔力:
var log = Function.prototype.bind.call(console.log, console);
log.apply(console, ["this", "is", "a", "test"]);
//-> "thisisatest"
Run Code Online (Sandbox Code Playgroud)
Mic*_*son 165
这个console.log问题的一个简单解决方案是在JS代码的开头定义以下内容:
if (!window.console) window.console = {};
if (!window.console.log) window.console.log = function () { };
Run Code Online (Sandbox Code Playgroud)
这适用于所有浏览器.当调试器未激活时,这将为console.log创建一个虚函数.当调试器处于活动状态时,方法console.log已定义并正常执行.
Ste*_*son 13
我知道这是一个非常古老的问题但是觉得这增加了如何处理控制台问题的有价值的替代方案.在调用console.之前放置以下代码.*(所以你的第一个脚本).
// 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;
}
}
}());
Run Code Online (Sandbox Code Playgroud)
参考:https :
//github.com/h5bp/html5-boilerplate/blob/v5.0.0/dist/js/plugins.js
Joh*_*ohn 10
console.log仅在控制台打开时定义.如果要在代码中检查它,请确保在窗口属性中检查它
if (window.console)
console.log(msg)
Run Code Online (Sandbox Code Playgroud)
这会在IE9中引发异常,无法正常工作.不要这样做
if (console)
console.log(msg)
Run Code Online (Sandbox Code Playgroud)
在阅读了Marc Cliament上面评论的文章之后,我现在将我的通用跨浏览器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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
114620 次 |
| 最近记录: |