Skip to content

Instantly share code, notes, and snippets.

@torifat
Created November 18, 2011 20:36
Show Gist options
  • Save torifat/1377676 to your computer and use it in GitHub Desktop.
Save torifat/1377676 to your computer and use it in GitHub Desktop.
Detect Browser & OS
var e = {
ie: function() {
return e._populate() || this._ie;
},
ie64: function() {
return e.ie() && this._win64;
},
firefox: function() {
return e._populate() || this._firefox;
},
opera: function() {
return e._populate() || this._opera;
},
safari: function() {
return e._populate() || this._safari;
},
chrome: function() {
return e._populate() || this._chrome;
},
windows: function() {
return e._populate() || this._windows;
},
osx: function() {
return e._populate() || this._osx;
},
linux: function() {
return e._populate() || this._linux;
},
iphone: function() {
return e._populate() || this._iphone;
},
_populated: false,
_populate: function() {
if (e._populated) return;
e._populated = true;
var i = navigator.userAgent;
var f = /(?:MSIE.(\d+\.\d+))|(?:(?:Firefox|GranParadiso|Iceweasel).(\d+\.\d+))|(?:Opera(?:.+Version.|.)(\d+\.\d+))|(?:AppleWebKit.(\d+(?:\.\d+)?))/.exec(i);
var h = /(Mac OS X)|(Windows)|(Linux)/.exec(i);
var g = /\b(iPhone|iP[ao]d)/.exec(i);
e._win64 = !!(/Win64/.exec(i));
if (f) {
e._ie = f[1] ? parseFloat(f[1]) : NaN;
if (e._ie && document.documentMode) e._ie = document.documentMode;
e._firefox = f[2] ? parseFloat(f[2]) : NaN;
e._opera = f[3] ? parseFloat(f[3]) : NaN;
e._safari = f[4] ? parseFloat(f[4]) : NaN;
if (e._safari) {
f = /(?:Chrome\/(\d+\.\d+))/.exec(i);
e._chrome = f && f[1] ? parseFloat(f[1]) : NaN;
} else e._chrome = NaN;
} else e._ie = e._firefox = e._opera = e._chrome = e._safari = NaN;
if (h) {
if (h[1]) {
var j = /(?:Mac OS X (\d+(?:[._]\d+)?))/.exec(i);
e._osx = j ? parseFloat(j[1].replace('_', '.')) : true;
} else e._osx = false;
e._windows = !!h[2];
e._linux = !!h[3];
} else e._osx = e._windows = e._linux = false;
e._iphone = g;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment