Java Reference
In-Depth Information
else if (document.all)
{
browser = “Internet Explorer”;
version = “6-”;+
if (window.XMLHttpRequest)
{
version = “7+”;
}
}
else if (window.sidebar)
{
browser = “Firefox”;
version = “1+”;
}
document.write(browser + “ “ + version);
</script>
</body>
</html>
Save this example as
ch6_examp6.htm
.
The page looks at which BOM and JavaScript properties the browser supports and, based on that, makes
a rough guess as to the browser type. So the fi rst lines checks to see if the browser's window object has
the opera property.
if (window.opera)
{
browser = “Opera”;
version = “5+”;
if (window.opera.setPreference)
{
version = “9”;
}
}
Because only Opera supports the
opera
property, it is safe to assume this is at least Opera version 5.
The inner
if
statement looks to see if the
window.opera
object supports the
setPreference
method;
this method is only supported by Opera version 9.
Next you have a test for the document object's all property, a property supported by IE 4+ and Opera 7+.
else if (document.all)
{
browser = “Internet Explorer”;
version = “6-”;
if (window.XMLHttpRequest)
{
version = “7+”;
}
}
Since you've already tested for Opera, you don't have to worry about false results from this script. To
see if the browser is an IE 7+ browser, check the
window
object's
XMLHttpRequest
property. The only