Categories:

The onerror event of the window object

Last updated: Jan 2nd, 2009

In this tutorial, lets examine a rather secretive event handler of JavaScript that fires whenever a JavaScript error occurs in a page. Using it, we can uniformly suppress all JavaScript errors on the page, or to create customized error dialogs.

Understanding the onerror event

The onerror event fires whenever an JavaScript error occurs (depending on your browser configuration, you may see an error dialog pop up). The onerror event is attached to the window object, a rather unusual place to take refuge in, but for good reason. It is attached this way so it can monitor all JavaScript errors on a page, even those in the <head> section of the page. Recall that event handlers can be inserted inside tags, like the below example with the onClick event handler:

<a href="http://cnn.com" onClick="alert('hi')">CNN</a>

Since onClick events react to a link being clicked on, they are naturally inserted inside the <a> tag. The onerror event, however, unlike most event handlers, cannot be inserted inside any tag. It can't, since there doesn't exist a "window" tag. Since no such tag exists in HTML, the onerror event can only be defined inside your JavaScript code as a property of the window object:

<script type="text/javascript">
window.onerror=function(){
 //code to run when error has occured on page
</script>

The code on the right is an anonymous function that contains any code you wish to execute when the event fires. A picture (or in this case, an actual code) is worth a thousand words, so before anything else, lets first see an example that alerts "an error has occurred!" when a js error occurs in a page:

<head>
<script type="text/javascript">

window.onerror=function(){
 alert('An error has occurred!')
}
</script>

<script type="text/javascript">
document.write('hi there'
</script>
</head>

In the above example, the careless JavaScript programmer had forgotten to close the document.write() method with a closing parentheses. Click here to see what happens. As you can see, not only did the usual error box pop up (if you're using IE and depending on your browser settings), our custom alert message is shown as well.

The placement of the onerror code is important if you wish to successfully intercept all scripting errors on the page- it should be placed at the very top of the page (proceeding any other JavaScript code) and wrapped around in its own <script> tags.