Skip to content

Instantly share code, notes, and snippets.

@berstend
Last active March 27, 2021 20:21
Show Gist options
  • Save berstend/081a9c5eb714a76c98e5690ab0b6226e to your computer and use it in GitHub Desktop.
Save berstend/081a9c5eb714a76c98e5690ab0b6226e to your computer and use it in GitHub Desktop.
Parse chrome/chromium version from user agent string and semver compare

Minimal utilties for parsing the version number of chromium based browsers.

const currentVersion = chromiumVersion.fromUserAgent() // => "91.0.4460.0"
chromiumVersion.is(currentVersion).newerThan("88.0.4298.0") // => true
chromiumVersion.fromUserAgent()
// => "91.0.4460.0"

chromiumVersion.fromString('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/88.0.4298.0 Safari/537.36')
// => "88.0.4298.0"

chromiumVersion.semver('91.0.4460.0')
// => {major: 91, minor: 0, build: 4460, patch: 0}

chromiumVersion.is("91.0.4460.0").newerThan("91.1")
// => false

chromiumVersion.is("91.0.4460.0").newerThan("91.0.4460.0")
// => false

chromiumVersion.is("91.0.4460.0").newerEqualThan("91.0.4460.0")
// => true
const chromiumVersion = (() => {
const compare = (newVer = "", oldVer = "") => {
const oldParts = oldVer.split(".");
const newParts = newVer.split(".");
for (let i = 0; i < newParts.length; i++) {
const a = ~~newParts[i]; // parse int
const b = ~~oldParts[i]; // parse int
if (a > b) return 1;
if (a < b) return -1;
}
return 0;
};
const is = (a) => ({
newerThan: (b) => compare(a, b) === 1,
newerEqualThan: (b) => [1, 0].includes(compare(a, b)),
olderThan: (b) => compare(a, b) === -1,
olderEqualThan: (b) => [-1, 0].includes(compare(a, b)),
});
const semver = (versionStr = "") => {
const [major, minor, build, patch] = versionStr.split(".").map((x) => ~~x); // parse int
return { major, minor, build, patch };
};
const fromString = (str = "") => (str.match(/Chrome\/(?<version>[\d.]+)?/) || { groups: {} }).groups.version;
const fromUserAgent = () => fromString(navigator?.userAgent);
return { compare, is, semver, fromString, fromUserAgent };
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment