DEV Community

@kon_yu
@kon_yu

Posted on

Using JavaScript to determine whether the client is iOS or Android

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"
}
Enter fullscreen mode Exit fullscreen mode

Usage

const os = getMobileOS()
# console.log(os) => 'Android'
# console.log(os) => 'iOS'
# console.log(os) => 'Other'
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (4)

Collapse
 
n3bb3z4r profile image
Óscar 'Nebe' Abad

I implemented this in that way for TS:

export const checkIphone = () => {
  const u = navigator.userAgent
  return !!u.match(/iPhone/i)
}
export const checkAndroid = () => {
  const u = navigator.userAgent
  return !!u.match(/Android/i)
}
export const checkIpad = () => {
  const u = navigator.userAgent
  return !!u.match(/iPad/i)
}
export const checkMobile = () => {
  const u = navigator.userAgent
  return !!u.match(/Android/i) || !!u.match(/iPhone/i)
}
export default {
  checkIphone,
  checkAndroid,
  checkIpad,
  checkMobile,
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
gopeeey profile image
gopeeey

Hi. Thank you.

Collapse
 
maintobias profile image
MainTobias

Does that detect apple silicon?

Collapse
 
konyu profile image
@kon_yu • Edited

I tried to do navigator.platform with Chrome in my M2 mac.
I got MacIntel in spite of using apple silicon.
In view of the above we can't apple silicon with that snippet .