3

I created some test code to open a new window and attempt to catch javascript errors in the new window, from the parent window. The problem is that it only works in 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>
...

All of test.html code:

<script>
alert('test');s //error on the s
</script>

Forefox will catch this, but Chrome and IE do not. All 3 browsers will open the new window, but the error alert only displays in Firefox. Each of the browsers' consoles also show the error.

Why don't Chrome and IE catch it?

Is there some other way to make those 2 browsers catch the errors?

Edit: I also tried add w.location.href after the onerror code, because I thought that maybe the onerror code was executed too late. This did not affect my results. Firefox was still the only one to catch the error.

<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>
Ryan
  • 1,135
  • 1
  • 13
  • 28

3 Answers3

1

I did a little searching, it seems the return value of window.open() of Chrome and IE are not act as normal/original window.

It seems the reason is about security, the following post is about chrome extension, but it may help:

window.open returns undefined in chrome extension

Community
  • 1
  • 1
Oscar
  • 59
  • 5
  • Thanks, that did help. I wonder if there is an alternative way. I tried injecting the javascript in the same way as that post, but it did not work. – Ryan Jun 28 '13 at 17:59
  • I decided to print out my `w` variable. In Chrome it says `[object Window]' and IE says `[object]`. So it seems at least in Chrome it is a normal window, maybe? – Ryan Jun 28 '13 at 18:33
  • I think it is a real `[object Window]` but it won't work as normal `window` maybe because of security concern or implementation concern. I am not sure, but I think you should find some way to workaround. – Oscar Jun 29 '13 at 16:53
0

Your best bet is going to be to wrap any code in the new window in a try/catch block. Catch the errors then send them back as such:

catch ... {
    window.opener.console.log(message);    
}
mmmeff
  • 1,025
  • 9
  • 20
0

Try with adding some timeout

setTimeout(function(){w.onerror = function(msg, file, line) { alert('error'); };}, 3000)