views:

264

answers:

2

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: alt text

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

+3  A: 

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)

Daniel Vassallo
is there any way to do this at a global level, like how you have global SEH for Windows apps? Is the `onerror` event something of the sort?
psychotik
Or even better, you could just `document.write()` the `exception` object as it's `toString()` method will return `TypeError: 'junkVariable' is undefined`, giving more info as to what type of error was thrown.
Eli Grey
@Elijah Grey: Thanks, I wasn't aware of that. Will edit my answer.
Daniel Vassallo
Great -- thanks! FWIW, onerror has the following arguments: msg, url, linenumber
psychotik
@psychotik: Yes, you can get the error message from the `msg` param.
Daniel Vassallo
FYI -- this doesn't work in Chrome. http://code.google.com/p/chromium/issues/detail?id=7771
psychotik
http://www.quirksmode.org/dom/events/error.html <-- this doesn't work a lot of places, but `try { } catch( ){ }` around your code does, :)
Dan Beam
A: 

http://stackoverflow.com/questions/361635/debugging-javascript-in-ie7

Dan Beam
thanks, but that's not what I'm looking for. I want to specifically access the contents of the error details in IE or error console in other browsers.Alternately, figuring out how to create a global exception handler equivalent for JavaScript would help too...I'll update my post.
psychotik