isLinux
Checks if the current platform is Linux.
1/**
2 * Checks if the current platform is Linux.
3 *
4 * @returns True if running on Linux, false otherwise.
5 */
6export function isLinux(): boolean {
7 if (typeof navigator === 'undefined') {
8 return false;
9 }
10
11 return /Linux/i.test(navigator.userAgent) && !/Android/i.test(navigator.userAgent);
12}
Accurate Platform Differentiation
Explicitly excludes Android from Linux detection, reducing false positives from mobile devices.
Lightweight Implementation
Uses straightforward regular expressions without reliance on external libraries.
Safe in Non-Browser Contexts
Protects against runtime errors in SSR or test environments with a
typeof navigator
check.
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 Linux user agent', () => {
11 Object.defineProperty(navigator, 'userAgent', {
12 value: 'Mozilla/5.0 (X11; Linux x86_64)',
13 configurable: true,
14 });
15 expect(isLinux()).toBe(true);
16});
17
18test('returns false for Android user agent (also Linux)', () => {
19 Object.defineProperty(navigator, 'userAgent', {
20 value: 'Mozilla/5.0 (Linux; Android 10)',
21 configurable: true,
22 });
23 expect(isLinux()).toBe(false);
24});
25
26test('returns false for Windows user agent', () => {
27 Object.defineProperty(navigator, 'userAgent', {
28 value: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
29 configurable: true,
30 });
31 expect(isLinux()).toBe(false);
32});
33
34test('returns false when navigator is undefined', () => {
35 const originalNavigator = globalThis.navigator;
36 delete (globalThis as any).navigator;
37
38 expect(isLinux()).toBe(false);
39
40 globalThis.navigator = originalNavigator;
41});
Common Use Cases
Tailoring Features for Linux Users
Enable or adjust behavior for Linux-specific environments (e.g., file system paths, fonts).
OS-Based Analytics
Track application usage by platform for insight into Linux user adoption.
Platform-Specific Bug Fixes
Apply Linux-specific patches or workarounds where needed.
Install Instructions or UI Labels
Dynamically show Linux commands or shortcuts in guides or tooltips.