There are a number of web browsers available today (and have been for long time), with each of them having a set of adventages and disadventages. Through, the web browsers are trying to implement a common set of features and comply with standard, it is not completely achieved yet. Hence, developer should take care to write scripts which are cross-platform supported and give optimum readability to end-users.

While scripting, developers can do detection of browser version or object detection to detect if the code works in a particular browser.

Browser version

The browser version can be detected by using Javascript BOM object window.navigator.appName, window.navigator.appVersion and window.navigator.userAgent. More information on these objects are in Javascript BOM object, navigator section, of this tutorial. Executing the code after checking for the browser and it’s version, in which users open the page, works for most popular browsers. But if an user is using any obscure browsers, or new browsers which might come up in future, the page might result in error messages or script might not open at all. Also userAgent, appName, appVersion values can be spoofed by end user to wrong values or nothing at all. Hence checking browser version while scripting is not a good option.

Object detection

A better option then using the navigator is to check if the object (method, array or property) which is used in the code is supported in the browser. For example, attachEvent() is the functionality supported in IE while same is written as addEventListener() in other browsers. Hence checking in IF condition, if the method is supported or not, makes the script work in all browsers. This condition check can be done to all methods, properties…etc which are not supported in all browsers or versions.

Syntax for attachEvent() method

if(attachEvent){

      //code here for IE

}else{

      //Code here for other browsers.

}

 

›› go to examples ››