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)
returnstrue/false
whether the string contained in the argumentua
hits the regular expression of/android/i
or not.
Top comments (4)
I implemented this in that way for TS:
Hi. Thank you.
Does that detect apple silicon?
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 .