Thursday, April 30, 2009

Detecting browser type using javascript



Many different browsers (e.g FireFox, IE,chrome,opera,safari)are available for displaying webpages. Each and every browser will have their own way of rendering content of webpage, and script (e.g javascript) execution also will vary based on the script engine implemented with them.

So it is very difficult to design a webpage which looks/works good in all browsers.
But anyway we should make the website to look good in all browser to reach maximum users.

So even we can write separate code for each browser and we can call it is based on the browser type of the user. And therefore a function for finding the browser type of the user is necessary.

Find below a sample javascript function for finding browser type.

function getbrowsertype()
{
var BrowserAgent;
BrowserAgent=navigator.userAgent;
var BrowserType="";
try
{
if ((BrowserAgent.indexOf("Firefox")!=-1))
{
BrowserType="firefox";
}
else
{
BrowserType="others";
}
}
catch(Exception)
{
BrowserType="others";
}
return BrowserType;




The above sample code will just detect whether the browser is firefox or others.

You can enhance it to include all other browsers also.
The try/catch is necessary here as the browser finding code supported by one browser may not be supported by another.

More Articles...

1 comment:

Vishal Raj said...

A lot more kind of browser detection can be added to the list



Thanks for visiting our blog


twitterrss facebook linkedin YouTube subscribe


Subscribe via email

Enter your email address: