Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

isMac

Checks if the current platform is macOS.

TypeScript
Copied!
1/**
2 * Checks if the current platform is macOS.
3 *
4 * @returns True if running on macOS, false otherwise.
5 */
6export function isMac(): boolean {
7  if (typeof navigator === 'undefined') {
8    return false;
9  }
10
11  return /Macintosh|Mac OS X/i.test(navigator.userAgent);
12}
  • Simple and Efficient Check

    Utilizes a concise regular expression to match macOS identifiers in the user agent string.

  • Platform-Safe Guard

    Includes a typeof navigator check to ensure compatibility with server-side rendering or non-browser environments.

  • Case-Insensitive Matching

    Uses the /i flag to account for inconsistencies in casing within user agent strings.

Tests | Examples

TypeScript
Copied!
1const originalUserAgent = navigator.userAgent;
2
3afterEach(() => {
4  Object.defineProperty(navigator, 'userAgent', {
5    value: originalUserAgent,
6    configurable: true,
7  });
8});
9
10test('returns true for macOS user agent', () => {
11  Object.defineProperty(navigator, 'userAgent', {
12    value: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)',
13    configurable: true,
14  });
15  expect(isMac()).toBe(true);
16});
17
18test('returns false for Windows user agent', () => {
19  Object.defineProperty(navigator, 'userAgent', {
20    value: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
21    configurable: true,
22  });
23  expect(isMac()).toBe(false);
24});
25
26test('returns false when navigator is undefined', () => {
27  const originalNavigator = globalThis.navigator;
28  delete (globalThis as any).navigator;
29
30  expect(isMac()).toBe(false);
31
32  globalThis.navigator = originalNavigator;
33});

Common Use Cases

  • Customizing Keyboard Shortcuts

    Enable macOS-specific shortcuts (e.g., Cmd instead of Ctrl) in web apps.

  • Applying macOS-Specific Styling

    Adjust font rendering or UI elements to better match macOS system aesthetics.

  • Analytics and Usage Tracking

    Segment usage data by platform to analyze macOS user behavior separately.

  • Workaround for OS-Specific Bugs

    Detect macOS to apply known fixes or adjustments for platform-specific browser issues.

Codebase: Utilities -> Platforms -> isMac | Yevhen Klymentiev