HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Detect the user's OS in the browser with JavaScript

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptuserdetectwiththebrowser

Problem

I was recently implementing a hotkeys feature for this website (hint use or Ctrl to see what I'm talking about), and I needed to detect the user's operating system in the browser. Seems simple, right? Yet, as with many things in the browser, it's more nuanced than you may think.
The most common answer online, and the one I was vaguely aware of, is based on the use of the Navigator.platform property. It's straightforward, too:
All we do here is take the value, use String.prototype.toLowerCase(), and check if it contains the string mac. If it does, we know the user is on a Mac.
Cool. Except, MDN says it's deprecated and no longer recommended for use. <br/> So much for that solution!
<baseline-support featureId="ua-client-hints">

Solution

const isMac = navigator.platform.toLowerCase().includes('mac');

isMac; // true if the user is on a Mac, false otherwise


All we do here is take the value, use String.prototype.toLowerCase(), and check if it contains the string mac. If it does, we know the user is on a Mac.
Cool. Except, MDN says it's deprecated and no longer recommended for use. <br/> So much for that solution!
<baseline-support featureId="ua-client-hints">
</baseline-support>
The consensus about the bleeding edge solution seems to revolve around Navigator.userAgentData, with some debate surrounding the need to use NavigatorUAData.getHighEntropyValues(). While the latter doesn't seem strictly necessary in most cases, the former seems relatively promising.
The problem in this case is the exact opposite of the previous one: support for this is pretty limited (at the time of writing only Chrome and Edge support it). So, while it may be a future solution, it's not at this time.

Code Snippets

const isMac = navigator.platform.toLowerCase().includes('mac');

isMac; // true if the user is on a Mac, false otherwise
const isMac = navigator.userAgentData?.platform === 'macOS';

isMac; // true if the user is on a Mac, false otherwise
const isMac = /mac/i.test(navigator.userAgent);

isMac; // true if the user is on a Mac, false otherwise

Context

From 30-seconds-of-code: browser-os-detection

Revisions (0)

No revisions yet.