Detecting iPhone or Android User on Your Website (JavaScript)

When you’re building a website, it’s always in the best interest of your end-user to be conscious of mobile views. This is generally called “mobile-responsive” development.
Both iPhone and Android environments and web browsers are almost always changing, which can be super frustrating in the development world. Just recently, iOS Safari added a search bar to the bottom of the view which obstructs the bottom of most websites.
What happens if you had bottom tab navigation for mobile users? Or a sliding drawer that’s now hidden?
Luckily, there’s a way for developers to determine whether a user is visiting with an iPhone or Android device, using the following code:
// detect if it's an Android device
const ua = navigator.userAgent.toLowerCase()
const isAndroid = ua.includes('android')
console.log(`The user is on an Android: ${isAndroid}`)const isIPhone = (navigator.userAgent.match(/iPhone/i)) ||(navigator.userAgent.match(/iPod/i))
console.log(`The user is on an iPhone: ${isIPhone}`)
Based on the values of isIPhone
or isAndroid
, you can now customize your UI so it’s specific to the OS being used by our user.
The following example is using React and Material UI styling. If it’s an Android or iPhone, the class mobileHeaderExtraSpace
is applied:
<div className={`${isAndroid || isIPhone ? classes.mobileHeaderExtraSpace : ''}`}></div>
Caution: It may also be helpful to apply breakpoints to any styles being applied with these variables, just in case it considers a Mac to be an “iPhone”.