Sunday, March 30, 2008

Checking OS and Browser with Javascript


I've ran into cases where different browsers and even the same browsers but on different OS's respond differently to CSS attributes. So in some cases it's best to check for the type of OS and browser and apply attributes accordingly. I recently had to deal with this issue for the Firefox browser on Mac.




It turns out that having an HTML element with a CSS opacity attribute interferes with Flash graphics on the web page if it lays over it. As far as I noticed this only happens currently when using Firefox on Mac. Since opacity wasn't a requirement and wasn't of importance I decided to take it out on that browser/OS combination. This is done by code like the following:





function checkOSBrowser() {
if(navigator.platform.indexOf("Mac") || navigator.userAgent.indexOf("Firefox"))
document.getElementById("myElem").style.opacity = "0.8";
}




To review, navigator.platform returns the current OS and navigator.userAgent returns the running browser name. It is generally better to use indexOf() or search() to look for the desired OS or browser than to use an exact match because if anything slightly changed with an exact match the match would fail. Take "Mac" for example. If you run navigator.platform on a Mac machine with Intel processors, the output would be "MacIntel" not "Mac." So if you don't care exactly what kind of Mac is running you should just use the indexOf() or search() functions provided by the Javascript String.