Monday, December 3, 2007

Web Browser Compatibility !!!!

Developing on a web application is not easy if you intend to have the product compatible with all the available browsers in the universe for some new browser or its clone comes to life everyday.

This article is about how can one know which browser is being used by the end-user and how one can customize the code in accordance the same, be it IE or Mozilla Firefox or Safari or blah blah blaaaaaaaaaaaah !!!

The end-user browser can be determined by using navigator.appname

The following code illustrates the same:


<html>
<head>
<script type="text/javascript">
function navigatorName()
{
alert(navigator.appName);
}
</script>
</head>

<body onload="navigatorName()">
<div id="browserContents">
</div>
</body>
</html>


When the page gets loaded, the onload feature will call the javascript function navigatorName() which will display the alert box with the name of the browser as the message.

Now, inside the function navigatorName, we can write the logic that would make our code browser specific


<html>
<head>
<script type="text/javascript">
function navigatorName()
{
if(navigator.appName == "Netscape")
{
document.getElementById("browserContents").innerHTML = "Netscape";
}
else if(navigator.appName == "Microsoft Internet Explorer")
{
document.getElementById("browserContents").innerHTML = "MS IE";
}
else
{
document.getElementById("browserContents").innerHTML = "Some Browser";
}
}
</script>
</head>

<body onload="navigatorName()">
<div id="browserContents">
loading . . .
</div>
</body>
</html>

Here, when the body part of the page has been loaded, the browser calls the function navigatorName(). This function checks the browser being used, and in accordance to that, replaces the contents of the div with id browserContents appropriate contents by making use of the function document.getElementById("browserContents").innerHTML.

No comments: