Home arrow JavaScript arrow Page 5 - Exception Handling in JavaScript: Addressing Browser Incompatibilities
JAVASCRIPT

Exception Handling in JavaScript: Addressing Browser Incompatibilities


Not all browsers handle all code the same way. Differences can be addressed with JavaScript exceptions. These may not be the best way under all circumstances, but you'll find it worthwhile to examine this approach.

Author Info:
By: Alejandro Gervasio
Rating: 4 stars4 stars4 stars4 stars4 stars / 11
October 11, 2005
TABLE OF CONTENTS:
  1. · Exception Handling in JavaScript: Addressing Browser Incompatibilities
  2. · JavaScript-based http requests: implementing cross-browser object instantiation
  3. · Cross-browser object instantiation: browser detection through exceptions
  4. · Proprietary event handlers: implementing browser-independent event handling
  5. · Assigning events to objects: using exceptions to manipulate event handlers

print this article
SEARCH DEVARTICLES

Exception Handling in JavaScript: Addressing Browser Incompatibilities - Assigning events to objects: using exceptions to manipulate event handlers
(Page 5 of 5 )

As I said before, JavaScript exceptions are useful enough to be applied in different conditions. Particularly when working with event handlers, exceptions can be implemented directly, in order to deal with proprietary event handling methods. Considering the above listed example, which checks for support of specific methods, it’s feasible to write a new script that utilizes exceptions to handle raised errors. Here’s what it looks like:

// Event Handler assignation using exceptions
var obj=document.getElementsByTagName('div')[0];
if(!obj){alert('Failed to get object!')};
try{
    // browser is Firefox, Nestcape, etc
    // use addEventListener() method
    obj.addEventListener('click',processEvent,false);
}
// catch thrown error
catch(e){
    try{
        // browser is Internet Explorer
        // use attachEvent() method
        obj.attachEvent('onclick',processEvent);
    }
    // catch thrown error
    catch(e){
        alert('Failed to add event handler');
    }
}
function processEvent(){
    alert('Event handler successfully attached!');
}

There are several points worth mentioning about the above code. First, the script attempts to attach to the <div> element an “onclick” event handler through the “addEventListener()” method, by executing the code within a “try” block.  As with XMLHTTP objects, if the code is successfully processed, the handler is tied to the proper object. Otherwise, if the attaching method is not supported by the JavaScript parser, an error will be triggered and trapped inside the corresponding “catch” block.

Returning to program flow, a new “try” block is used to attach the event handler by using the “attachEvent()” method, which is supported by Internet Explorer. Finally, if all attempts fail, a warning is displayed since no handler was successfully attached. Before I continue with the code explanation, a brief note is in order here: there is a known issue with the “addEventListener()” method for IE 5 on Mac, which fails silently when invoked, so if you’re still getting many visitors using this browser, consider using another cross-browser solution that addresses this particular case too.

By this point, hopefully you’ve understood the underlying logic of the above script, so there is plenty of room to experiment with different browser proprietary methods, for the sake of solving other incompatibilities. Of course, the whole script can be easily customized through a containing function, which would be much more useful than its current incarnation. As usual, feel free to use the above example and introduce your own improvements.

For the sake of completeness, below is the full example, which also roughly implements exceptions to attach an “onload” event handler to the “window” object:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>EXCEPTION-BASED EVENT HANDLING ASSIGNATION</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-
8859-1" />
<script language="javascript">
// Event Handler assignation using exceptions
function processEvent(){
    alert('Event handler successfully attached!');
}
function addEventHandler(){
    var obj=document.getElementsByTagName('div')[0];
    if(!obj){return false};
    try{
        // browser is Mozilla, Nestcape, etc.
        // use addEventListener() method
        obj.addEventListener('click',processEvent,false);
    }
    // catch thrown error
    catch(e){
        try{
            // browser is Internet Explorer
            // use attachEvent() method
            obj.attachEvent('onclick',processEvent);
       }
        // catch thrown error
        catch(e){
            alert('Failed to add event handler');
        }
    }
}
// assign 'onload' event handler to window object
try{
    window.addEventListener('load',addEventHandler,false);
}
catch(e){
    try{
        window.attachEvent('onload',addEventHandler);
    }
    catch(e){
        alert('Failed to add event handler');
    }
}
</script>
</head>
<body>
<div>EXAMPLEPAGE</div>
</body>
</html>

Conclusion

Finally, we’re done. Over this series I’ve discussed in detail the use of exceptions in JavaScript programs, ranging from core concepts to advanced implementation, such as multiple errors handlers, custom error object creation and practical application on form validation and cross-browser scripts.

Hopefully, the overall experience has been instructive enough for those developers that want to start out quickly using JavaScript exceptions within client-side applications. Even when exception-based programs take up some additional lines of code, giving a try is really worthwhile, due mainly to the fact that errors are handled through a more professional and robust built-in mechanism. There you have it, so take advantage of it!


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
JAVASCRIPT ARTICLES

- Project Nashorn to Make Java, JavaScript Wor...
- JavaScript Virus Attacks Tumblr Blogs
- Google Releases Stable Dart Version, JavaScr...
- Khan Academy Unveils New JavaScript Learning...
- Accessing Nitro? There`s an App for That
- JQuery 2.0 Leaving Older IE Versions Behind
- Fastest JavaScript Engine Might Surprise You
- Microsoft Adjusting Chakra for IE 10
- Brendan Eich: We Don`t Need Google Native Cl...
- An Overview of JavaScript Statements
- An Overview of JavaScript Operators
- Overview of JavaScript Variables
- More of the Top jQuery Social Plugins
- The Top jQuery Social Plugins
- More of the Top jQuery Slider Plugins

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials