Created
January 17, 2024 14:09
-
-
Save ortense/cecac34af74509f01575f578f9da2d47 to your computer and use it in GitHub Desktop.
get browser name by user agent
This file contains 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
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