Another little post to illustrate something that I came across during the 9 to 5. As us technophiles probably know, there is an overwhelming difference in interpretation of web standards between browsers hence a vast range of different visual output from the same codebase. This is annoying for the user they won’t understand why the same page is fine in Firefox but screwy in IE. And for us coders it is a major headache trying to write code that is good everywhere!

Some of the time you can write unanimous code that does work in all browsers, but other times you will need to have special cases depending on the browser. So we need to detect the browsers accurately; our friend javascript can return a number of values for browser detection such as navigator.Appname and navigator.AppCodeName. But these can return similar values for different browsers so I find the best way to go is to parse the navigator.userAgent string. This will always be different between browsers, to detect Mozilla Firefox for example; use this command:

var is_firefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;

The variable can then simply be used in an if statement to determine what browser you are using. You can detect any browser like this, just substitute firefox here with chrome, safari etc.

Happy coding :)

Thanks to David Walsh for the heads up on this one.