| home / programming / javascript / sniffing / 2 | [previous] |
|
|
By this point you have an idea on how to go about detecting various browsers. But once you have that knowledge, how do you apply it so that you can do something useful with it? If, for example, you are looking to customize the layout of your Web page based on the CSS properties supported (or not supported) by particular browsers, you can use object detection to redirect the browser to the appropriate .css file using a simple set of if else statements in JavaScript.
In the following example code, we take the values (either "true" or "false") from the variables we set up and when a match is made, the appropriate .css stylesheet is selected.
<html>
<head>
<title>Object Sniffer Code for Netscape 6 and 7</title>
<script>
// netscape browsers
var is_nn6 = (navigator.product == 'Gecko') && (!window.find)?true:false;
var is_nn7 = (navigator.product == 'Gecko') && (window.find)?true:false;
if (is_nn6)
{document.write("<link rel=\"stylesheet\" href=\"nn6.css\"/>")}
else if (is_nn7)
{document.write("<link rel=\"stylesheet\" href=\"nn7.css\"/>")}
else
{document.write("<link rel=\"stylesheet\" href=\"default.css\"/>")}
</script>
</head>
<body>
The text on the page will be colored differently depending on which browser
is used.
<ul>
<li>If Netscape 6 is being used, the text color will be orange
<li>If Netscape 7 is being used, the text color will be pink
<li>If something other than these browsers are used, the <em>background</em>
color will be red
</ul>
Netscape (Gecko-based) browsers:<br>
<script>
document.write("Netscape 6: " + is_nn6 + "<br />");
document.write("Netscape 7: " + is_nn7 + "<br />");
</script>
</body>
</p>
</body>
</html>
The writer wishes to acknowledge the work of Mark Wilton-Jones and his browser sniffing tutorial at http://www.howtocreate.co.uk/tutorials/jsexamples/sniffer.html, to which this article is indebted.
| home / programming / javascript / sniffing / 2 | [previous] |
Created: March 27, 2003
Revised: August 12, 2003
URL: URL: http://webreference.com/programming/javascript/sniffing/2