Friday 5 September 2008

Google Chrome - user-agent (UA)

For anyone interested in browser detection, here is Google Chrome's "useragent" string:
Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.13

You can get it by simply typing "about:" in the omnibox ("address" bar)
or alternatively by adding the following to your <head> section.


<script language="javascript">
function showUA()
{
userAgent = navigator.userAgent;
alert("UserAgent: " + userAgent);
}

window.onload=showUA;
</script>



So something similar to the following could be used to detect which browser you are using:


<html>
<head>
<script language="javascript">
function setBrowser()
{
var browser="unknown";
var userAgent = navigator.userAgent.toLowerCase();
if (userAgent.indexOf("opera") > -1)
browser="Opera";
else if (userAgent.indexOf("konqueror") > -1)
browser="Konqueror";
else if (userAgent.indexOf("firefox") > -1)
browser="Firefox";
else if (userAgent.indexOf("netscape") > -1)
browser="Netscape";
else if (userAgent.indexOf("msie") > -1)
browser="Internet Explorer";
else if (userAgent.indexOf("chrome") > -1)
browser="Chrome";
else if (userAgent.indexOf("safari") > -1)
browser="Safari";

var brDiv=document.getElementById("browser");
brDiv.innerHTML="<b>" + browser + "</b>";
}

window.onload=setBrowser;
</script>
</head>
<body>
You are using:
<div id="browser"></div>
</body>
</html>


If you are using one of those popular browsers its name should show up in the empty "browser" div in the body section. Note that the order of the tests is critical. For instance, both Opera and Netscape useragent strings contain "msie" so it is necessary to test for those browsers before testing for Internet Explorer.

Of course the above script is certainly very basic and we could take things a step further and not only retrieve browser name but also browser version for instance, or test for other things like whether the browser is Java-enabled, which Javascript version is available, which Flash Player version is installed or which operating system is being used.

Let me just share a couple of links which cover this more comprehensive approach to Javascript browser sniffing:
Browser sniffing: takes an in-depth look at how to sniff all major and lots of minor browsers.
JavaScript Browser Sniffer: the "ultimate" mainstream browser detection script.

Have fun!

No comments:

Online Marketing
Add blog to our blog directory blog search directory Blog Directory Blogarama - The Blog Directory