check if user agent is desktop in typescript

To check if a user agent belongs to a desktop device, we can check for the presence of certain keywords in the user agent string. Here's an example in TypeScript:

index.ts
function isDesktopUserAgent(): boolean {
  const userAgent = navigator.userAgent.toLowerCase(); // get user agent string in lower case

  const keywordsToCheck = ['windows', 'macintosh', 'linux', 'x11']; // keywords to check for desktop user agent
  const isDesktop = keywordsToCheck.some((keyword) => userAgent.includes(keyword)); // check if any of the keywords are present in user agent
  
  return isDesktop;
}
415 chars
9 lines

In the code above, we first get the user agent string in lower case using navigator.userAgent.toLowerCase(). We then define an array of keywords to check for desktop user agent - on desktop devices, the user agent string usually includes the name of the operating system (e.g. Windows, Macintosh, Linux, X11). We then use the some() method to check if any of the keywords are present in the user agent string - if any of them are present, we can assume that it's a desktop user agent and return true.

gistlibby LogSnag