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.ts415 chars9 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