isWindows
Checks if the current platform is Windows.
1/**
2 * Checks if the current platform is Windows.
3 *
4 * @returns True if running on Windows, false otherwise.
5 */
6export function isWindows(): boolean {
7 if (typeof navigator === 'undefined') {
8 return false;
9 }
10
11 return /Windows/i.test(navigator.userAgent);
12}
Lightweight and Fast
Uses a simple regex to identify Windows in the user agent string with minimal performance cost.
Safe for Non-Browser Environments
Includes a
typeof navigator
check to prevent errors during SSR or headless testing.Broad Compatibility
Detects all common variants of Windows thanks to the general
/Windows/i
pattern.
Tests | Examples
1const originalUserAgent = navigator.userAgent;
2
3afterEach(() => {
4 Object.defineProperty(navigator, 'userAgent', {
5 value: originalUserAgent,
6 configurable: true,
7 });
8});
9
10test('returns true for Windows user agent', () => {
11 Object.defineProperty(navigator, 'userAgent', {
12 value: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
13 configurable: true,
14 });
15 expect(isWindows()).toBe(true);
16});
17
18test('returns false for macOS user agent', () => {
19 Object.defineProperty(navigator, 'userAgent', {
20 value: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)',
21 configurable: true,
22 });
23 expect(isWindows()).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(isWindows()).toBe(false);
31
32 globalThis.navigator = originalNavigator;
33});
Common Use Cases
Platform-Specific UI Tweaks
Adjust interface elements for Windows conventions (e.g., scrollbars, fonts).
Conditional Feature Enablement
Enable or disable features known to behave differently on Windows browsers.
Usage Analytics by OS
Segment user metrics to track adoption or performance by Windows users.
Bug Workarounds
Detect Windows to apply fixes for OS-specific rendering or behavior issues.