isAndroid
Checks if the current platform is Android.
1/**
2 * Checks if the current platform is Android.
3 *
4 * @returns True if running on Android, false otherwise.
5 */
6export function isAndroid(): boolean {
7 if (typeof navigator === 'undefined') {
8 return false;
9 }
10
11 return /Android/i.test(navigator.userAgent);
12}
Lightweight Implementation
Uses a single regex check for the "Android" keyword, making it fast and efficient.
Safe for SSR and Non-Browser Environments
Includes a
typeof navigator
check to avoid runtime errors outside the browser.Case-Insensitive Matching
Uses
/Android/i
to handle variations in user-agent string casing across different devices or browsers.
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 Android user agent', () => {
11 Object.defineProperty(navigator, 'userAgent', {
12 value: 'Mozilla/5.0 (Linux; Android 10; SM-G973F)',
13 configurable: true,
14 });
15 expect(isAndroid()).toBe(true);
16});
17
18test('returns false for iPhone user agent', () => {
19 Object.defineProperty(navigator, 'userAgent', {
20 value: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X)',
21 configurable: true,
22 });
23 expect(isAndroid()).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(isAndroid()).toBe(false);
31
32 globalThis.navigator = originalNavigator;
33});
Common Use Cases
Applying Android-Specific Styles or Fixes
Adjust UI or layout to account for quirks on Android browsers or devices.
Platform-Specific Feature Control
Enable/disable features that behave differently or aren't supported on Android (e.g., file handling APIs, vibrations).
Usage Analytics and Debugging
Track Android user behavior separately in telemetry or A/B tests.
Mobile UI Optimization
Tailor touch targets, keyboard interactions, or performance settings specifically for Android users.