Using Javascript to detect Google Chrome to switch CSS

Jakob picture Jakob · Apr 20, 2012 · Viewed 36.4k times · Source

I have been playing around with different scripts, I found one that works for everything but Chrome... this is the code I have been using to differ in .CSS files. I tried just makeing the Browser name into "Chrome" But that did not work.

if (browser == 'Firefox') {
    document.write('<link rel="stylesheet" href="../component/fireFoxdefault.css" />');
}
if (browser == 'Safari') {
    document.write('<'+'link rel="stylesheet" href="../component/default.css" />');
}

Answer

T. Junghans picture T. Junghans · Apr 20, 2012

Use the following to detect chrome:

var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;

Source: http://davidwalsh.name/detecting-google-chrome-javascript

Update (2015-07-20):

The above solution does not always work. A more reliable solution can be found in this answer (see below). That being said, I would avoid browser detection and go with feature detection instead:

var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor); 

You can include a css file specifically for chrome like this:

if (isChrome) {
    document.write('<'+'link rel="stylesheet" href="../component/chromeDefault.css" />');
}

UPDATE (2014-07-29):

@gillesc has a more elegant suggestion for detecting Chrome which he posted in a comment below and it can also be viewed on this question.

var isChrome = !!window.chrome