问题描述
经测试发现问题只出现在:
1、原生IE8(其他版本IE模拟出的IE8无此问题)
2、从打开IE8没有开启过F12(曾经开启过又关闭的无此问题)
IE8报错“由于出现错误80020101而导致此项操作无法完成”,进而导致当前页面无法显示,同时整站所有页面都无法加载。
问题分析-IE8没有console对象
从上述症状分析,猜测应该跟IE8的开发者工具有关,说明代码中使用了IE开发者工具中提供的API接口或功能,而在没有开启F12时,因为没有相应接口导致报错。
通过开启F12发现输出了info信息,那就应该是代码中使用的console.info()导致的。
经检查发现IE8下当没有开启过F12时,window对象中没有console,遂使用console任何方法都会报错。
解决方案-IE下构造空console对象
增加兼容代码,若当前window中存在console对象则使用当前对象,不存在则新增window.console对象,将所有console函数定义为空函数。用以保证页面不会报错。
//兼容IE8的空console对象
window.console = window.console || {
log: $.noop,
debug: $.noop,
info: $.noop,
warn: $.noop,
exception: $.noop,
assert: $.noop,
dir: $.noop,
dirxml: $.noop,
trace: $.noop,
group: $.noop,
groupCollapsed: $.noop,
groupEnd: $.noop,
profile: $.noop,
profileEnd: $.noop,
count: $.noop,
clear: $.noop,
time: $.noop,
timeEnd: $.noop,
timeStamp: $.noop,
table: $.noop,
error: $.noop
};
新增兼容代码后,当IE8不能使用console时,也不会报错。美美的。
新问题-console对象不全
好景不长,没过多久测试组发现还有一些IE8版本报错,一看依然是console问题。
经测试发现,某些IE8版本下,在从来没有开启过F12的情况下,window对象下有console对象,遂骗过了上述兼容代码,但是它的console中只有log方法。而代码中使用了console.info,遂导致依然报错。
//测试IE8的console
var str = "window.console:\n";
for (var i in window.console) {
str += i + " : " + typeof (window.console[i]) + "\r\n";
}
alert(str);
运行结果:
WTF!
我总不能把代码改成检测console否含有info方法,天知道哪个版本的IE的哪个方法又兼容error方法但不兼容其他函数?
似乎解决方案只能重写console对象了
最终解决方案-重写console所有函数
将常用的console函数都重新包裹一遍,相当于hook原函数,内部判断是否可用。
window._console = window.console;//将原始console对象缓存
window.console = (function (orgConsole) {
return {//构造的新console对象
log: getConsoleFn("log"),
debug: getConsoleFn("debug"),
info: getConsoleFn("info"),
warn: getConsoleFn("warn"),
exception: getConsoleFn("exception"),
assert: getConsoleFn("assert"),
dir: getConsoleFn("dir"),
dirxml: getConsoleFn("dirxml"),
trace: getConsoleFn("trace"),
group: getConsoleFn("group"),
groupCollapsed: getConsoleFn("groupCollapsed"),
groupEnd: getConsoleFn("groupEnd"),
profile: getConsoleFn("profile"),
profileEnd: getConsoleFn("profileEnd"),
count: getConsoleFn("count"),
clear: getConsoleFn("clear"),
time: getConsoleFn("time"),
timeEnd: getConsoleFn("timeEnd"),
timeStamp: getConsoleFn("timeStamp"),
table: getConsoleFn("table"),
error: getConsoleFn("error"),
memory: getConsoleFn("memory"),
markTimeline: getConsoleFn("markTimeline"),
timeline: getConsoleFn("timeline"),
timelineEnd: getConsoleFn("timelineEnd")
};
function getConsoleFn(name) {
return function actionConsole() {
if (typeof (orgConsole) !== "object") return;
if (typeof (orgConsole[name]) !== "function") return;//判断原始console对象中是否含有此方法,若没有则直接返回
return orgConsole[name].apply(orgConsole, Array.prototype.slice.call(arguments));//调用原始函数
};
}
}(window._console));
完美的解决了IE中的console对象不完整导致的各种问题,同时也不影响高级浏览器的console功能。
——2015年6月11日19:06:45
让IE兼容console——“由于出现错误80020101而导致此项操作无法完成”的解决方案
标签:class style log com 代码 使用 http src java
原文:http://www.cnblogs.com/xxcanghai/p/4569926.html