Home >Web Front-end >JS Tutorial >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);
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); }
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'; }
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!