Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect Apple Watch via Javascript (e.g., User Agent)

I am trying to detect an Apple Watch via Javascript. However, the size/width and user agent don't give any definitive clues when compared to my iPhone 6. Here's the html:

<!DOCTYPE html>
<html lang="en">

<head>
<title>Watch Test</title>
</head>

<body>
    <div id="width">width</div>
    <div id="height">height</div>
    <div id="user_agent">user_agent</div>

    <script type="text/javascript">
        document.getElementById("width").innerHTML = "Width is '" + screen.width + "'";
        document.getElementById("height").innerHTML = "Height is '" + screen.height + "'";
        document.getElementById("user_agent").innerHTML = "User Agent is '" + navigator.userAgent + "'";
    </script>
</body>
</html>

My iPhone 6 running iOS 12.1.2 displays:

Width is '320'
Height is '568'
User Agent is 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1'

And my Apple Watch running WatchOS 5.1.2 displays:

Width is '320'
Height is '568'
User Agent is 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.0 Mobile/15E148 Safari/604.1'

The only difference is the version which will change in the future. I also looked at navigator.platform, but it is iPhone on both devices.

Any clues on how I might detect an Apple Watch?

like image 352
Steve A Avatar asked Jul 03 '26 05:07

Steve A


1 Answers

I got the same issue here and found a weird (and possibly not future-proof) workaround. You need to check if it supports playing AAC audio via HTML5 audio. As for now, it doesn't support any audio while all iPhones do.

  let a = document.createElement('audio');
  let supportsAAC =  !!(a.canPlayType && a.canPlayType('audio/mp4; codecs="mp4a.40.2"').replace(/no/, ''));
  let is_iphone = ['iPhone Simulator','iPhone'].includes(navigator.platform)
  return is_iphone && !supportsAAC

It definitely might change in the future, but I guess it's okay for now (it still holds true after 2 years). Also, there are probably other ways to detect this, as it doesn't seem to support videos either.

like image 174
unkaktus Avatar answered Jul 04 '26 19:07

unkaktus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!