I\'ve been searching around for code that would let me detect if the user visiting the website has Firefox 3 or 4. All I have found is code to detect the type of browser but
I was looking for a solution for myself, since jQuery 1.9.1 and above have removed the $.browser
functionality. I came up with this little function that works for me.
It does need a global variable (I've called mine _browser) in order to check which browser it is. I've written a jsfiddle to illustrate how it can be used, of course it can be expanded for other browsers by just adding a test for _browser.foo, where foo is the name of the browser. I did just the popular ones.
detectBrowser()
_browser = {};
function detectBrowser() {
var uagent = navigator.userAgent.toLowerCase(),
match = '';
_browser.chrome = /webkit/.test(uagent) && /chrome/.test(uagent) &&
!/edge/.test(uagent);
_browser.firefox = /mozilla/.test(uagent) && /firefox/.test(uagent);
_browser.msie = /msie/.test(uagent) || /trident/.test(uagent) ||
/edge/.test(uagent);
_browser.safari = /safari/.test(uagent) && /applewebkit/.test(uagent) &&
!/chrome/.test(uagent);
_browser.opr = /mozilla/.test(uagent) && /applewebkit/.test(uagent) &&
/chrome/.test(uagent) && /safari/.test(uagent) &&
/opr/.test(uagent);
_browser.version = '';
for (x in _browser) {
if (_browser[x]) {
match = uagent.match(
new RegExp("(" + (x === "msie" ? "msie|edge" : x) + ")( |\/)([0-9]+)")
);
if (match) {
_browser.version = match[3];
} else {
match = uagent.match(new RegExp("rv:([0-9]+)"));
_browser.version = match ? match[1] : "";
}
break;
}
}
_browser.opera = _browser.opr;
delete _browser.opr;
}
To check if the current browser is Opera you would do
if (_browser.opera) { // Opera specific code }
Edit Fixed the formatting, fixed the detection for IE11 and Opera/Chrome, changed to browserResult from result. Now the order of the _browser
keys doesn't matter. Updated jsFiddle link.
2015/08/11 Edit Added new testcase for Internet Explorer 12 (EDGE), fixed a small regexp problem. Updated jsFiddle link.