Getting Javascript Errors From Another Window - javascript

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>

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

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);
}

Try with adding some timeout
setTimeout(function(){w.onerror = function(msg, file, line) { alert('error'); };}, 3000)

Related

How to throw a javascript error during runtime via browser (Chrome)?

My objective: Test out my error handling functionality.
Temporary solution: Have a custom route: /error, which contains code which purposefully produces fatal error.
var a = undefined;
a.b.c // Breaks.
The above works, but I can't use it to test production site as the page is not required.
I was looking for a way to test it via the browser. I tried simply adding"
throw new Error("Custom error thrown here") to the console. That doesn't actually break it during runtime.
I tried adding a break point and adding the same code: throw new Error("Custom error thrown here"). That didn't work either.
Any other easier ways to do this rather than the above?
I was looking for a way where I can do it via browser only.
Thanks.
You did not clearly mention how and where the error should be thrown. I will assume that you can use a modified copy of your JavaScript file to throw errors. The modified file will reside on your computer and only be used when you're using Chrome developer tools. This feature is called Local Overrides. The steps are as follows:
Open the webpage
Open Chrome developer tools for that webpage
In Sources panel go to Overrides tab
Click Select folder for overrides and choose a folder on your computer
A warning appears on the webpage which reads "DevTools requests full access to ..." which you must allow
In Sources panel go to Page tab
Locate the file in which you need to inject the "throw error" code
Right click and choose Save for overrides
Now you can edit the copy of the file on your computer or from within developer tools. Insert the code that produces the error at the desired location. When you reload the page with developer tools open, Chrome will load the local copy of the JavaScript file and throw the error. The error thrown that way will contain the context from where it originated e.g. call stack. If the developer tools are closed then live copy will be used.
If I got your question right, this is How you can do it from the console:
var script_tag = document.createElement('script');
script_tag.type = 'text/javascript';
script_tag.text = 'throw new Error("Custom error thrown here")';
document.body.appendChild(script_tag);
Or if you want you can trigger it on click:
var script_tag = document.createElement('script');
script_tag.type = 'text/javascript';
script_tag.text = 'window.document.onclick = function() { throw new Error("Custom error thrown here")}';
document.body.appendChild(script_tag);
And then you click anywhere on the page, to throw the error;
I would use the exec function which actually takes string and runs the code within at compile time.
exec('a.b.c')
You won't be able to throw an error inside your application from the console, since you are out of scope of the app.
Having said that, one slightly awkward way you could do this is by adding a breakpoint at the start of the javascript file.
Reload the page and your app will pause at the breakpoint - you can then modify the code as you need - like adding a throw new Error("something...") - and save your edits.
Then allow the code to run and you will see your error.
A downside is if you reload the changes will be gone, but I believe it's as close as you can get to modifying code at runtime.
Add this code to your production code
window.addEventListener('err', () => {
throw new Error('break it');
})
and when you want to create an error simply
dispatchEvent(new Event('err'))
in the console
You can use a global variable, which is accessible from your app and from debug console.
if (window.shouldThrow) {
throw new Error("Custom error thrown here");
}
This way you can turn on/off the exception throwing using the window.shouldThrow variable.
Try this way to catch error detail on run time
try
{
var a = undefined;
a.b.c // Breaks.
}
catch ( e )
{
alert("Error: " + e.description );
}

Javascript function not defined in FireFox only - indeed_clk is not defined

I'm at a loss to figure out why a JavaScript function is not defined.
It works on all browsers, and all versions of FireFox on my dev machine. But the error occurs for some users running FireFox.
The external JavaScript include file is provided by Indeed.com.
The include file that contains the function definition (indeed_clk) is
<script type="text/javascript" src="http://www.indeed.com/ads/apiresults.js"></script>
This line appears immediately after the head elememt
Further down the page, the indeed_clk function is referenced using the following pattern
<a onmousedown = "indeed_clk(this,'7832');" href="landing page..." >Click to view</a>
The error message is "indeed_clk is not defined"
A sample page that demonstrates the rendered html and Javascript code is
http://www.contractsforgeeks.com/TechJobs/All_States/All_Cities.aspx
Any suggestions as to why the function would not be defined in FF, and not work only for certain machine configurations would be appreciated.
Try changing:
indeed_clk(this,'7832')
To:
indeed_clk(this,'7832');"
I found a solution/workaround to the problem, but still don't understand why the error occurs.
It seems that the presence of an error Handler causes an error (but only in FF for some users)
An error handler was hooked up
(document).ready ( errorHandling);
function errorHandling()
{
window.onerror = function (message, url, line) {
var msg = message + "\n" + " url:" + url + "\nline:" + line;
alert(msg);
}
Disabling the error handling enabled the missing indeed_clk function to be found.

how to catch ALL javascript errors with window.onerror? (including dojo)

this question is a follow-up to javascript: how to display script errors in a popup alert? where it was explained how to catch regular javascript errors using:
<script type="text/javascript">
window.onerror = function(msg, url, linenumber) {
alert('Error message: '+msg+'\nURL: '+url+'\nLine Number: '+linenumber);
return true;
}
</script>
I tried it and found out that dojo erros like this one:
TypeError: this.canvas is undefined dojo.js (Row 446)
were not reported using this method, which leads me to my question:
How can I report all javascript errors using window.onerror (especially dojo errors)?
It could be Dojo is using proper Error handling methods (i.e. try-catch blocks) which prevents the exception from bubbling up and reaching the window container, on which you have registered the error handler.
If so, there is no way for you to do this. No error is going past the catch block, so no error handler is being called.
As pointed out by the comments, you can also use browser-specific debugging APIs like the Venkman hook and do break-on-error -- a solution that usually only works for privileged code (thanks to #Sam Hanes).
You can also do On(require, 'error', function () {}); to add error handling on DOJO's asynchronous script loader -- another point mentioned in the comments by #buggedcom
you can write code like this:
var goErrHandler=window.onerror;
goErrHandler= function(msg, url, linenumber) {
console.log('Error message: '+msg+'\nURL: '+url+'\nLine Number: '+linenumber);
return true;
}
goErrHandler();
so in console you'll see some thing like this :
Error message: undefined
URL: undefined
Line Number: undefined
The better solution is to use try/catch, e.g.
try{
if(a=='a'){
}
}catch(e){
alert(e);
//or send to server
new Image().src='errorReport.php?e='+e;
}
Google Plus seems to use this.

Calling window.close in IE throws null or object not found error

I have a very wierd error cropping up in IE.
I am opening a window, with a specific url , and closing it immidiately, using the following code:
openSomething(guid)
{
my_window = window.open("outlook:"+guid,"mywindow","width=0,height=0");
my_window.close();
}
This script outputs things as expected, i.e this opens the right outlook mail needed, but IE window shows the error "my_window null or not an object".
Can someone please tell me what is wrong here??
That usually happens when the window is blocked by a/the popup blocker. You'll need to make sure that window.open actually returns a window:
my_window = window.open("outlook:"+guid,"mywindow","width=0,height=0");
if (my_window && my_window.close) {
my_window.close();
}

Programmatically access webpage error details in browsers

Is there some way to access webpage warning/error details using JavaScript?
For instance, errors in IE show up in the bottom left corner like so:
I would like to able to access the details of this error (in IE as well as other browsers if possible) using JavaScript.
Any suggestions?
EDIT: I'm not looking for debuggers. I want to access the content of the error details/error console. Alternately, figuring out how to create a global exception handler equivalent for JavaScript would help too
You may want to use the window.onerror event. You can consider this event as a sort of global exception handler. The value returned by onerror determines whether the browser displays a standard error message. If you return false, the browser displays the standard error message in the JavaScript console. If you return true, the browser does not display the standard error message. (Source)
<script type="text/javascript">
window.onerror=function(msg, url, line){
alert('An error has occurred' + msg);
return true;
}
</script>
<script type="text/javascript">
// Syntax error
document.write('hi there'
</script>
You can also use traditional exception handling in JavaScript to catch run-time errors.
try
{
document.write(junkVariable)
}
catch (exception)
{
document.write(exception)
}
The output of the above would be:
‘junkVariable’ is undefined
EDIT: As noted by psychotik's comment, the window.onerror event does not work in Google Chrome. (Source)

Categories

Resources