bowser-ultralight
Version:
Lightweight(er) browser detector, basically a trimmed down version of bowser, specfically made for Atlassian
147 lines (126 loc) • 3.16 kB
JavaScript
import browserParsersList from "./parser-browsers.js";
/**
* The main class that arranges the whole parsing process.
*/
class Parser {
/**
* Create instance of Parser
*
* @param {String} UA User-Agent string
* @param {Boolean} [skipParsing=false] parser can skip parsing in purpose of performance
* improvements if you need to make a more particular parsing
* like {@link Parser#parseBrowser} or {@link Parser#parsePlatform}
*
* @throw {Error} in case of empty UA String
*
* @constructor
*/
constructor(UA, skipParsing = false) {
if (UA === void 0 || UA === null || UA === "") {
throw new Error("UserAgent parameter can't be empty");
}
this._ua = UA;
/**
* @typedef ParsedResult
* @property {Object} browser
* @property {String|undefined} [browser.name]
* Browser name, like `"Chrome"` or `"Internet Explorer"`
* @property {String|undefined} [browser.version] Browser version as a String `"12.01.45334.10"`
*/
this.parsedResult = {};
if (skipParsing !== true) {
this.parse();
}
}
/**
* Get UserAgent string of current Parser instance
* @return {String} User-Agent String of the current <Parser> object
*
* @public
*/
getUA() {
return this._ua;
}
/**
* Test a UA string for a regexp
* @param {RegExp} regex
* @return {Boolean}
*/
test(regex) {
return regex.test(this._ua);
}
/**
* Get parsed browser object
* @return {Object}
*/
parseBrowser() {
this.parsedResult.browser = {};
const browserDescriptor = browserParsersList.find((_browser) => {
if (typeof _browser.test === "function") {
return _browser.test(this);
}
if (_browser.test instanceof Array) {
return _browser.test.some((condition) => this.test(condition));
}
throw new Error("Browser's test function is not valid");
});
if (browserDescriptor) {
this.parsedResult.browser = browserDescriptor.describe(this.getUA());
}
return this.parsedResult.browser;
}
isMobile() {
return this.test(
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i
);
}
/**
* Get parsed browser object
* @return {Object}
*
* @public
*/
getBrowser() {
if (this.parsedResult.browser) {
return this.parsedResult.browser;
}
return this.parseBrowser();
}
/**
* Get browser's name
* @return {String} Browser's name or an empty string
*
* @public
*/
getBrowserName(toLowerCase) {
if (toLowerCase) {
return String(this.getBrowser().name).toLowerCase() || "";
}
return this.getBrowser().name || "";
}
/**
* Get browser's version
* @return {String} version of browser
*
* @public
*/
getBrowserVersion() {
return this.getBrowser().version;
}
/**
* Parse full information about the browser
* @returns {Parser}
*/
parse() {
this.parseBrowser();
return this;
}
/**
* Get parsed result
* @return {ParsedResult}
*/
getResult() {
return Object.assign({}, this.parsedResult);
}
}
export default Parser;