JavaScript: How to detect if device is iOS?

While developing an application understanding which devices and operating systems your users are on is crucial for optimizing your site or application for various platforms. Detecting whether a user is on an iOS device is particularly useful when you need to deliver a tailored experience for iPhones, iPads, or iPods, as these devices have unique capabilities and restrictions.

Why Detect iOS Devices?
Detecting whether a user is on an iOS device can be beneficial in several situations:

  • Responsive Design Adjustments: iOS devices have unique display characteristics (like the notch on iPhones and certain viewport size limitations). Detecting iOS allows you to tailor your design accordingly.
  • Touch Events: iOS devices rely heavily on touch events, so you may want to adjust interactions for a better user experience.
  • Feature Detection: Some features, such as the behavior of Safari on iOS, may differ from other browsers or devices. You may need to modify behavior based on the OS to ensure a smooth experience.

Method 2: Using the User-Agent Property

The most common approach for detecting iOS devices is by examining the navigator.userAgent property. The user agent property provides detailed information about the browser, operating system, and device type. For iOS devices, this string contains the word “iPhone”, “iPad”, or “iPod”.

Here is a JavaScript snippet that detects if the device is running iOS:

var isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
if (isIOS) {
  console.log('This is a IOS device');
} else {
  console.log('This is Not a IOS device');
}

Here variable isIOS return true if its iOS device and false if its not.

Explanation:

  • navigator.userAgent: This property contains a string that represents the browser’s identity. It includes details about the browser and the operating system.
  • /iPad|iPhone|iPod/: This regular expression checks if the user agent contains the keywords “iPad”, “iPhone”, or “iPod”, which are unique to iOS devices.

Why window.MSStream is excluded?
We need to exclude window.MSStream as Microsoft injected the word iPhone in IE11’s userAgent in order to try and fool Gmail. More info about this is here and here.

Method 2: Using the Platform Property

Similar to navigator.userAgent, navigator.platform property can also be used to detect the underlying platform. For iOS, the platform will often be one of the following:

  • iPhone
  • iPad
  • iPod

Here is a JavaScript snippet that detects if the device is running iOS using navigator.platform :

var isIOS = /iPad|iPhone|iPod/.test(navigator.platform) && !window.MSStream;
if (isIOS) {
  console.log('This is a IOS device');
} else {
  console.log('This is Not a IOS device');
}

Liked this article? You wanna check Moment JS’s useful functions.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *