Skip to content

Instantly share code, notes, and snippets.

@r3b
Created November 18, 2013 19:42
Show Gist options
  • Save r3b/7534069 to your computer and use it in GitHub Desktop.
Save r3b/7534069 to your computer and use it in GitHub Desktop.
Minimalist browser userAgent parsing based on data from https://developer.mozilla.org/en-US/docs/Browser_detection_using_the_user_agent
//Minimalist browser name/version parsing based on data from
//https://developer.mozilla.org/en-US/docs/Browser_detection_using_the_user_agent
function createBrowserRegex(browser){
return new RegExp('\\b('+browser+')\\/([^\\s]+)');
}
function createBrowserTest(userAgent, positive, negatives){
var matches = BROWSER_REGEX[positive].exec(userAgent);
negatives=negatives||[];
if(matches && matches.length && !negatives.some(function(negative){return BROWSER_REGEX[negative].exec(userAgent)})){
return matches.slice(1,3);
}
}
var BROWSER_REGEX=["Seamonkey", "Firefox", "Chromium", "Chrome", "Safari", "Opera"].reduce(function(p,c){
p[c]=createBrowserRegex(c);
return p;
},{});
BROWSER_REGEX["MSIE"]=new RegExp(";(MSIE) ([^\\s]+)");
var BROWSER_TESTS=[
["MSIE"],
["Opera", []],
["Seamonkey", []],
["Firefox", ["Seamonkey"]],
["Chromium", []],
["Chrome", ["Chromium"]],
["Safari", ["Chromium","Chrome"]]
].map(function(arr){
return createBrowserTest(navigator.userAgent, arr[0], arr[1]);
});
BROWSER_TESTS.reduce(function(p,c){return (c)?c:p;}, "UNKNOWN");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment