loading...

Using JavaScript to determine whether the client is iOS or Android

konyu profile image @kon_yu ・1 min read

Introduction.

Contents of this function

  • Use ES2015 arrow functions.
  • When a web page is displayed in a browser, the OS of the access source is determined based on the user agent.
  • Reflects iOS, Android and other operating systems using regular expressions

User agents for each OS are available at here.

The iPad is now iPadOS instead of iOS from 13, and if you're set to display a website for a PC, it won't include the iPad in the UserAgent, so you'll have to make a tricky decision.
ref: https://stackoverflow.com/a/57924983/4480860

const getMobileOS = () => {
  const ua = navigator.userAgent
  if (/android/i.test(ua)) {
    return "Android"
  }
  else if (/iPad|iPhone|iPod/.test(ua))
     || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1){
    return "iOS"
  }
  return "Other"
}

Usage

const os = getMobileOS()
# console.log(os) => 'Android'
# console.log(os) => 'iOS'
# console.log(os) => 'Other'

Explanation of supplementary regular expressions

An example of /android/i.test(ua) used in the described functions

  • /android/ is the body of the regular expression
  • The "i" in /android/i is a regular expression flag and does not detect case.
    • It will be compatible with Android, ANDROID and aNdRoId.
    • The /android/i checks if any part of the string to be validated contains "android" regardless of the case of the string.
  • The test method of /android/i.test(ua) returns true/false whether the string contained in the argument ua hits the regular expression of /android/i or not.

Discussion

pic
Editor guide