Home > Web Front-end > JS Tutorial > How Can I Reliably Detect if a Device is Running iOS?

How Can I Reliably Detect if a Device is Running iOS?

Barbara Streisand
Release: 2024-12-21 12:37:09
Original
942 people have browsed it

How Can I Reliably Detect if a Device is Running iOS?

Can I Detect Whether a Device is Running on iOS?

Introduction

While feature detection is typically preferred over device detection, there may be scenarios where it becomes necessary to determine whether a device is running on iOS.

Detection Methods

User Agent Sniffing (Not Recommended):

Warning: User agent sniffing can be unreliable and is susceptible to manipulation. However, for legacy purposes, you can use the following code to check for iOS in the user agent string:

var iOS = !window.MSStream && /iPad|iPhone|iPod/.test(navigator.userAgent);
Copy after login

Platform Detection:

A more robust method involves verifying the device platform using navigator.platform:

function iOS() {
  return [
    'iPad Simulator',
    'iPhone Simulator',
    'iPod Simulator',
    'iPad',
    'iPhone',
    'iPod'
  ].includes(navigator.platform)
  || (navigator.userAgent.includes("Mac") && "ontouchend" in document);
}
Copy after login

This approach also accounts for iPad devices on iOS 13, where the user agent string is identical to MacOS.

Inferring iOS Version:

While user agent strings can be used to infer the iOS version, it's worth noting that this approach is unreliable due to potential future deprecations. As an alternative, you can employ history check against iOS-introduced APIs to infer the OS version. However, this approach also has its limitations in terms of reliability.

function iOSversion() {

  if (iOS()) {
    if (window.indexedDB) { return 'iOS 8 and up'; }
    if (window.SpeechSynthesisUtterance) { return 'iOS 7'; }
    if (window.webkitAudioContext) { return 'iOS 6'; }
    if (window.matchMedia) { return 'iOS 5'; }
    if (window.history && 'pushState' in window.history) { return 'iOS 4'; }
    return 'iOS 3 or earlier';
  }

  return 'Not an iOS device';
}
Copy after login

The above is the detailed content of How Can I Reliably Detect if a Device is Running iOS?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template