Last active
February 13, 2018 07:22
-
-
Save lamchau/5be23873151338e022953719884ec16c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const bowser = require('bowser'); | |
const FULL_SEMVER = /^(\d+)\.(\d+)\.(\d+)[\+|\-]?(.*)?$/; | |
const MAJOR_MINOR_VERSION = /^(\d+)\.(\d+)[\+|\-]?(.*)?$/; | |
const ANY_DIGIT = /^(\d+)$/; | |
function parseVersion(str) { | |
const [, major, minor, patch, metadata] = | |
FULL_SEMVER.exec(str) || | |
MAJOR_MINOR_VERSION.exec(str) || | |
ANY_DIGIT.exec(str) || | |
[]; | |
return { | |
major, | |
minor, | |
patch, | |
metadata, | |
}; | |
} | |
function getVersion(version) { | |
const { | |
major, | |
minor | |
} = parseVersion(version); | |
if (major === undefined && minor === undefined) { | |
return undefined; | |
} | |
if (minor === undefined) { | |
return `${major}.0`; | |
} | |
return `${major}.${minor}`; | |
} | |
function getBrowserInfo(str) { | |
const { | |
name, | |
version, | |
osname, | |
osversion | |
} = bowser._detect(str || window.navigator.userAgent); | |
return { | |
browser_version: getVersion(version), | |
browser_name: String(name).toLowerCase(), | |
os_name: osname, | |
os_version: osversion, | |
}; | |
} | |
const isEqual = require('lodash').isEqual; | |
function test(input, expected) { | |
const actual = getBrowserInfo(input); | |
if (isEqual(actual, expected)) { | |
console.log(`[ ok]: ${JSON.stringify(actual)}`); | |
} else { | |
console.log(`[fail]: ${JSON.stringify(actual)} !== ${JSON.stringify(expected)}`); | |
} | |
} | |
test('windows', { | |
browser_version: undefined, | |
browser_name: '', | |
os_name: 'Windows', | |
os_version: undefined | |
}); | |
test(null, { | |
"browser_version": "63.0", | |
"browser_name": "chrome", | |
"os_name": "macOS", | |
"os_version": "10.11.6" | |
}); | |
test('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55 Safari/537.36', { | |
"browser_version": "55.0", | |
"browser_name": "chrome", | |
"os_name": "macOS", | |
"os_version": "10.11.6" | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment