Monday, 14 March 2011

JavaScript: browser detection


JavaScript is a great programming language and it is widely used by web developers. Personally I use JavaScript sparingly because I prefer to use VBScript whenever I can, but I must admit some times JavaScript can really simplify things a lot.
However, there is a well known issue about JavaScript. Despite the wide use and spread of JavaScript snippets, the scripts could pose compatibilities issues. For instance, some old browsers could be not completely compatible. In those cases, it is quite useful to use the navigator object in order to detect the user browser.

The navigator object
First of all, please notice that there is not a public standard for the navigator object, however all major browsers interpret it. We can use the object to fetch browser information such as name, version, platform, agent or cookies status.
The object properties are:
appCodeNameThe code name of the browser.
appNameThe name of the browser
appVersionBrowser version
cookieEnabledBoolean that indicates whether the browser has cookies enabled
languageReturns the default language of the browser version (NS and Firefox only)
mimeTypes[]An array of all MIME types supported by the client (NS and Firefox only)
platform[]The platform of the client's computer
pluginsAn array of all plug-ins currently installed on the client (NS and Firefox only)
systemLanguageReturns the default language of the operating system (IE only)
userAgentThe user-agent header
userLanguageReturns the preferred language setting of the user (IE only)

The code
How we use it? Simple, just copy the following snippet wherever it's needed:
<div id="example"></div>

<script type="text/javascript">

txt = "Browser CodeName: " + navigator.appCodeName + "<br>";
txt+= "Browser Name: " + navigator.appName + "<br>";
txt+= "Browser Version: " + navigator.appVersion + "<br>";
txt+= "Cookies Enabled: " + navigator.cookieEnabled + "<br>";
txt+= "Platform: " + navigator.platform + "<br>";
txt+= "User-agent header: " + navigator.userAgent + "<br>";


The above code will show the relevant properties of the user browser. It is quite clear that the navigator object could be used to detect the user browser and so use scripts that the browser can understand. Using a simple if statement you can execute code accordingly.

Is it Firefox or IE?
Let's see an example:
<script type="text/javascript">

if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
  your code here

if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){
 your code here

You can then execute different JavaScript code according to the user browser.

Please let me know your thoughts, as usual!

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.