我创建了一些测试代码来打开一个新窗口并尝试从父窗口中捕获新窗口中的javascript错误。问题是它只适用于Firefox:
...
<body>
<script>
//open new window and keep a reference to it
var w = window.open('test.html', '_blank'); //test.html has an error
//add the error listener
w.onerror = function(msg, file, line) { alert('error'); };
</script>
</body>
...
所有 test.html 代码:
<script>
alert('test');s //error on the s
</script>
Forefox会抓住这个,但Chrome和IE不会。所有3个浏览器都将打开新窗口,但错误警报仅显示在Firefox中。每个浏览器的控制台也会显示错误。
为什么Chrome和IE没有抓住它?
是否有其他方法可以让这两个浏览器捕获错误?
修改
我也尝试在错误代码之后添加w.location.href
,因为我认为可能是错误的代码执行得太迟了。这并没有影响我的结果。 Firefox仍然是唯一能够发现错误的人。
<script>
var w = window.open('test2.html', '_blank'); // test 2 is a page with no errors
w.onerror = function(msg, file, line) { alert('error'); };
w.location.href = 'test.html'; // the page with the error
</script>
答案 0 :(得分:1)
我进行了一些搜索,似乎Chrome和IE的window.open()
的返回值不是正常/原始window
。
似乎原因在于安全性,以下帖子是关于chrome扩展,但它可能会有所帮助:
答案 1 :(得分:0)
最好的办法是将新窗口中的任何代码包装在try / catch块中。抓住错误然后将其发回:
catch ... {
window.opener.console.log(message);
}
答案 2 :(得分:0)
尝试添加一些超时
setTimeout(function(){w.onerror = function(msg,file,line){alert('error');};},3000)