Skip to content

Instantly share code, notes, and snippets.

@ortense
Created January 17, 2024 14:09
Show Gist options
  • Save ortense/cecac34af74509f01575f578f9da2d47 to your computer and use it in GitHub Desktop.
Save ortense/cecac34af74509f01575f578f9da2d47 to your computer and use it in GitHub Desktop.
get browser name by user agent
export type BrowserName = 'edge' | 'chrome' | 'firefox' | 'safari' | 'opera' | 'ie';
export type BrowserCheck = (userAgent: UserAgent) => boolean;
export type UserAgent = string;
const BrowserCheckMap: Record<BrowserName, BrowserCheck> = Object.freeze({
edge: agent => /Edg/.test(agent),
chrome: agent => /Chrome/.test(agent),
firefox: agent => /Firefox/.test(agent),
safari: agent => /Safari/i.test(agent) && !/Chrome/i.test(agent),
opera: agent => /Opera/.test(agent),
ie: agent => /Trident|MSIE/.test(agent),
});
export function getBrowserName(userAgent: UserAgent): BrowserName | 'unknown' {
const browser = Object.keys(BrowserCheckMap).find(
(name: BrowserName) => BrowserCheckMap[name](userAgent)
) as BrowserName;
if (browser) return browser;
return 'unknown';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment