isFirefox
Determines if the current browser is Firefox.
1/**
2 * Determines if the current browser is Firefox.
3 *
4 * @returns True if running in Firefox, false otherwise.
5 */
6export function isFirefox(): boolean {
7 if (typeof navigator === 'undefined') return false;
8 return /firefox/i.test(navigator.userAgent);
9}
Minimal and Efficient Logic
The implementation uses a concise regular expression to match Firefox with minimal overhead.
Case-Insensitive Matching
Utilizes the
/i
flag to ensure consistent detection regardless of capitalization in the user agent string.Environment Safety Check
Includes a
typeof navigator
check to prevent runtime errors outside browser environments.
Tests | Examples
1const originalNavigator = global.navigator;
2
3afterEach(() => {
4 global.navigator = originalNavigator;
5});
6
7test('returns true for Firefox userAgent', () => {
8 // @ts-ignore
9 global.navigator = {
10 userAgent: 'Mozilla/5.0 (Windows NT 10.0; rv:92.0) Gecko/20100101 Firefox/92.0'
11 };
12 expect(isFirefox()).toBe(true);
13});
14
15test('returns false for Chrome userAgent', () => {
16 // @ts-ignore
17 global.navigator = {
18 userAgent:
19 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/96.0.4664.45 Safari/537.36'
20 };
21 expect(isFirefox()).toBe(false);
22});
23
24test('returns false if navigator is undefined', () => {
25 // @ts-ignore
26 delete global.navigator;
27 expect(isFirefox()).toBe(false);
28});
Common Use Cases
Browser-Specific Styling or Fixes
Apply targeted fixes for Firefox-specific rendering quirks (e.g., grid behavior or input focus).
Feature Detection Fallbacks
Provide alternatives when Firefox lacks or differs in support for APIs like
WebRTC
,AudioContext
, orscrollIntoView
.Custom Performance Tweaks
Optimize behavior for Firefox’s rendering engine where performance differs from other browsers.
Debugging and Logging Enhancements
Customize diagnostics or telemetry depending on whether the user is on Firefox.