Here is browser detection code in JavaScript

Simple JavaScript code for browser detection:

 * Browser detection
 * @Created-On 2007-11-27 23:46:51
function detectBrowser(){
		return "Opera";
	}else if(navigator.userAgent.indexOf("MSIE")!=-1){
		return "MSIE";
	}else if(navigator.userAgent.indexOf("Navigator")!=-1){
		return "Netscape";
	}else if(navigator.userAgent.indexOf("Firefox")!=-1){
		return "Firefox";
	}else if(navigator.userAgent.indexOf("Safari")!=-1){
		return "Safari";

About 15 years out of date.

The userAgent is a free format field that can be set to contain ANYTHING AT ALL by the browser’s owner - at least it can with Internet Explorer, Firefox, Mozilla, and Netscape. Opera changes the userAgent automatically to whatever you want to present to different web sitesw with a choice of identifying itself as IE, Firefox, or Opera.

Using code like that is the easiest way to totally stuff up your web page.

Use feature sensing when necessary in your code - NEVER test user enterable free format fields to try to work out what browser it is.

That code might have been alright in 1990 but not in the year 2000.

My Favourite way of doing this :slight_smile:

if (document.all && !window.opera)
       // Internet Explorer
else if (window.opera)
       // Opera
else if (navigator.userAgent.indexOf("Safari") != -1)
       // Safari
else if (!document.all && !window.opera)
       // Firefox/Mozilla, Netscape and other browsers

Im sure it can be improved upon, especially the recognition of safari.

Yes, 100% right.
And I use this code at 1990; quote from DHML books,
which is hot at that time.:stuck_out_tongue:

So, what is the way of coding to detecting browser in current age???

You don’t need to know which of the several differnt browsers that it is, you just need to know if it supports the code you weant to run.

For example to test if a browser supports Document Object Model access via the standard getElementById() method you use:

if (document.getElementById) {
alert(‘browser supports getElementById’);
} else {
alert(‘antiquated browser that doesn’t understand 21st century code’);

You do the same thing for any code where a browser may or may not support the a given command - test if the browser recognises the command and if so then you know you can use it.

Well, actually I am in need to give width to overlay div, and found that different browsers have different width in px, due to which scrollbar is generated…

That, shoorace, would be a CSS issue, not a JavaScript issue. Why don’t you start a thread in the CSS board (and then link this thread to it in the new one) so we can check it out?

The scrollbar widths can all be changed from the operating system configuration so there is no guarantee of a particular width for a given browser making browser detection completely pointless for this anyway. A CSS solution will work even when JavaScript is disabled.