Home / Advanced JavaScript Tutorials / The onerror event of the window object

 

 

CodingForums
Having trouble with scripting? Visit our help forum to get the answers you need.

Jump to...
-Free JavaScripts
-JS tutorials
-JS Reference
-DHTML/CSS

-Free applets
-Web Tutorials
-Link to Us!

- CSS Drive
- PHP Resources
- Hotels & Vacations
- Bad credit cards
- JavaScript Menus

 

Red_CurlyC035.gif (285 bytes) Creating custom JavaScript error dialog boxes

In this section, we'll look at how to create custom error boxes that replace the default one in the event of a js error. This box, unlike the default box, pops up only once, even if there are multiple errors on the page:

<script>
function errorbox(){
errorwindow=window.open("","","width=250,height=125")
errorwindow.document.write('<title>Error Window</title><center><b>A JavaScript error(s) has occurred on this page</b><Br><form><input type="button" value="Close window" onClick="window.close()"></form></center>')
errorwindow.document.close()
errorwindow.document.bgColor="white"
return true
}
window.onerror=errorbox
</script>

Click here to see the above script used on a page containing js errors

There really is nothing new in the above script; it opens up a new window, dynamically constructs a basic document inside of it to inform the user of the js error(s), returns true inside function errorbox to cancel the loading of the default error box, and that's that.

If you're really ambitious, you can actually create a custom error box that, when closed, sends the information regarding the errors (error message, line number etc) to you, providing you with an easy way to debug your scripts with the help of your surfers. The idea is to store all the error information into an array, and connect the form button inside the error window to your usual form submission script, so all the error info is submitted to you when the error box is closed. I'll help you get started by writing the hardest part of such a script- storing the error messages into an array:

<script>
var. errorcontainer=new Array()
function reporterrorbox(msg, url, linenumber){
errorcontainer[errorcontainer.length]='Error message= '+msg+'\nURL= '+url+'\nLine Number= '+linenumber
return true
}
window.onerror=reporterrorbox
</script>

Just so I can get some sleep, I'll leave the rest of the code to you.

-Tutorial introduction
-Understanding the onerror event
-Using the onerror event to suppress JavaScript errors
-Retrieving additional information about a JavaScript error through scripting
-Creating custom JavaScript error dialog boxes


End of tutorial

http://javascriptkit.com
Copyright © 1997-2005 JavaScript Kit. NO PART may be reproduced without author's permission.