Browser and OS as a body class

I would like to have an OS and a browser in the body class. I need this for pixel style improvement, because fonts do not behave the same in different OS / Browser configurations. After some searching and experimenting. The only way I could think of is to use indexOf ...

var OSName="Unknown OS"; if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows"; if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS"; if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX"; if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux"; var agt=navigator.userAgent.toLowerCase(); if (agt.indexOf("opera") != -1) return 'Opera'; if (agt.indexOf("firefox") != -1) return 'Firefox'; if (agt.indexOf("safari") != -1) return 'Safari'; if (agt.indexOf("webkit") != -1) return 'Webkit'; if (agt.indexOf("msie") != -1) return 'Internet Explorer'; if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla'; 

I think this is not a very pretty solution. Is there any regex that can do this? Or is there a faster way to do this?

+4
source share
2 answers

You can use a regular expression, but that will not make it more beautiful.

In principle, scanning user agent strings for the / os / version browser will never be beautiful.

Here is something a little prettier with jQuery ...

 // Add some classes to body for CSS hooks // Get browser $.each($.browser, function(i) { $('body').addClass(i); return false; }); // Get OS var os = [ 'iphone', 'ipad', 'windows', 'mac', 'linux' ]; var match = navigator.appVersion.toLowerCase().match(new RegExp(os.join('|'))); if (match) { $('body').addClass(match[0]); }; 

This does not quite give you the same classes as above, but enough to distinguish between different OS and browser.

For example, you can target Firefox on Windows with ...

 body.windows.mozilla { background: blue; } 

Take a look!

Or use the plugin.

+6
source

for browser information, if jQuery is used, there is $.browser

http://api.jquery.com/jQuery.browser/

0
source

All Articles