|
|
Browser detection using JavaScript - Tip JavaScriptWith a little help from JavaScript, you can easily detect the browser used by visitors on your web site. Browser detection has several uses. It helps you analyze your visitors if you store this information in a database, which assists you in building visitor profiles for better web site maintenance. You can redirect visitors to browser specific pages or display browser specific content such as style sheets. The code described in this tip will concentrate on Netscape and Internet Explorer since they share more than 90% of the browser market. However, the code can be extended to detect other browsers.
<SCRIPT LANGUAGE="JavaScript" TYPE="TEXT/JAVASCRIPT">
<!--
function whichname()
{
var bname = navigator.appName;
alert("You are using " + bname);
}
//-->
</SCRIPT>
Clicking here will display your browser name
The crux of this code is the appName property of the navigator object. This property contains the name of the browser. We assign this to a variable bname and then display it using the alert method. (Simple enough?) Redirection based on browser detected by JavaScriptOkay, now that you have learnt browser detection, we shall see how to implement it to redirect visitors to different pages depending on their browser.
<SCRIPT LANGUAGE="JavaScript" TYPE="TEXT/JAVASCRIPT">
<!--
var bname = navigator.appName;
if (bname.search(/netscape/i) == 0)
{
window.location="nn.html";
}
else if (bname.search(/microsoft/i) == 0)
{
window.location="ie.html";
}
else
{
window.location="other_browsers.html";
}
//-->
</SCRIPT>
After assigning the browser name to bname, we search for the presence of specific words using JavaScript Regular Expressions. (JavaScript Regular expressions have been included in version 1.2 of the language and are based on those found in the Perl language. So if you were familiar with Perl, picking up the JavaScript regular expressions would be very simple).
Page contents: Know how to detect visitor browser using JavaScript code. Configure the code as per your requirements.
Page URL: http://www.webdevelopersnotes.com/tips/html/ browser_detection_using_javascript_tip_javascript.php3
|
|