Skip to content

Is iOS?

Working around Apple’s mobile OS

I’m working on a side project that uses the Web Audio API. However on iOS the Web Audio API can’t produce a sound if a device is muted. (I think this is a feature rather than a bug.) HTML 5 Audio plays sound no matter a device’s mute state, but you don’t get the same level of programmatic control that Web Audio affords.

A workaround is to use Web Audio but simultaneously play a silent audio file via HTML5 Audio.

This can be the subject of a future post. But first I needed to work out whether the user is running iOS. It’s simple enough, complicated only slightly by the fact that iPads run a version of desktop Safari. Here’s the code I’m using:

const user_agent = navigator.userAgent.toLowerCase();
const is_iOS =
user_agent.indexOf("iphone") > -1 ||
user_agent.indexOf("ipod") > -1 ||
user_agent.indexOf("ipad") > -1 || // This may not be required
(navigator.maxTouchPoints && /Mac/.test(navigator.platform)); // iPad running 'desktop' Safari

is_iOS returns truthy or falsey, letting us know whether the user is on iOS.

Good practice for tailoring your code to a particular browser is to use feature detection (as we do here with navigator.maxTouchPoints). However additionally querying navigator.userAgent for the presence of a string is fine too when we can’t rely soley on feature detection. Of course you may need to update the query in future if user agent or platform names change.

(An alternative to the playing-silent-HTML5-Audio workaround would be to instead read is_iOS’s value and print a helpful ‘Unmute your device’ message under the ‘Play’ button. Unfortunately there’s no API call you can make to get the mute state.)

You can run the iOS detection code here (courtesy of CodeSandbox).