Skip to content

Instantly share code, notes, and snippets.

@gcoop
Created January 14, 2011 11:19
Show Gist options
  • Save gcoop/779490 to your computer and use it in GitHub Desktop.
Save gcoop/779490 to your computer and use it in GitHub Desktop.
I still need to know what the client is!
// Feature detection rocks.
// But what if you want to display something different on a different browser?
// You still need to know what browser the client is in.
//
// For example thanks to modernizr I know geoLocation exists, but I also know that FF's
// Allow location bar isn't very obvious to the user and I want to provide some help.
// Thus I need to make sure I style the helper in the correct place. Using .firefox .geo-helper
// I place it top right but in chrome I can place it somewhere else.
window.BrowserDetection = (function (window,document,undefined) {
var browser,
docEle = document.documentElement,
browsers = [
"firefox",
"opera",
"android",
"iphone",
"ipad",
"webkit",
"msie",
"safari"
],
// Borrowed from somewhere on GitHub...
RX_TABLE = [
[ /^.*(Firefox|Chrome|chromeframe|Conkeror|SeaMonkey)\/(\d+\.\d+).*$/, "$1 $2"],
[ /^.*Firefox.*$/, "Firefox" ],
[ /^.*Opera.*Version\/(\d+\.\d+).*$/, "Opera $1" ],
[ /^.*Opera[\/ ](\d+\.\d+).*$/, "Opera $1" ],
[ /^.*Android (\d+\.\d+).*$/, "Android $1" ],
[ /^.*iPhone;.*OS (\d+(?:_\d+)*).*$/, "iPhone $1" ],
[ /^.*iPad;.*OS (\d+(?:_\d+)*).*$/, "iPad $1" ],
[ /^.*iPod;.*$/, "iPod" ],
[ /^.*Version\/(\d+\.\d+).*Safari.*$/, "Safari $1" ],
[ /^.*Qt\/(\d+\.\d+).*$/, "QtWeb $1" ],
[ /^.*WebKit.*$/, "WebKit" ],
[ /^.*Gecko.*$/, "Gecko" ],
[ /^.*MSIE (\d+\.\d+).*$/, "MSIE $1" ]
];
window.onload = function () {
BrowserDetection.init();
}
return {
init: function () {
for (var i = 0; i < browsers.length; i++) {
if (BrowserDetection.is(browsers[i])) {
docEle.className += " "+browsers[i];
}
}
},
getBrowser: function () {
if (typeof browser == 'undefined') {
browser = BrowserDetection.recognize(navigator.userAgent);
}
return browser;
},
recognize: function (name) {
for (var i = 0; i < RX_TABLE.length; ++i) {
var r = name.replace(RX_TABLE[i][0], RX_TABLE[i][1]);
if (r != name) {
return r.replace(/chromeframe/, "ChromeFrame").replace(/_/g, ".");
}
}
return "unknown";
},
is: function (name) {
if (BrowserDetection.getBrowser().toLowerCase().indexOf(name) !== -1) {
return true;
}
return false;
}
}
})(this, this.document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment