Skip to content

Instantly share code, notes, and snippets.

@wiledal
Last active July 19, 2023 17:36
Show Gist options
  • Save wiledal/92eb62e579fe3c03976395dd4b25d3e1 to your computer and use it in GitHub Desktop.
Save wiledal/92eb62e579fe3c03976395dd4b25d3e1 to your computer and use it in GitHub Desktop.
Get Browser Platform
import { getBrowserPlatform } from '@/src/lib/browser-platform/browser-platform';
const DESKTOP_UA =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36';
const IPHONE_UA =
'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1';
const ANDROID_UA =
'Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.91 Mobile Safari/537.36';
describe('browser-platform', () => {
it('gets the correct android platform', () => {
const result = getBrowserPlatform(ANDROID_UA);
expect(result).toBe('android');
});
it('gets the correct ios platform', () => {
const result = getBrowserPlatform(IPHONE_UA);
expect(result).toBe('ios');
});
it('gets the correct desktop platform', () => {
const result = getBrowserPlatform(DESKTOP_UA);
expect(result).toBe('desktop');
});
});
/**
* Get the current platform
*/
export const getBrowserPlatform = (userAgent?: string) => {
if (!userAgent && typeof navigator !== 'undefined') {
userAgent = navigator.userAgent;
}
if (!userAgent) {
return 'unknown';
}
const ua = userAgent.toLowerCase();
if (
['ipad', 'ipod', 'iphone'].some((t) => ua.includes(t)) ||
// iPadOS 13 registers as a Mac, however a mac with touch input does not exist (at time of writing), so it must be an iPad
(ua.includes('mac') && 'ontouchend' in window)
) {
return 'ios';
}
if (ua.includes('android')) {
return 'android';
}
return 'desktop';
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment