If you are still trying to check if is iOS or not, I recommend you to use this approach:
- Create a folder called
helper
- Create a file called
platform.ts
or platform.js
- Export the function
isIOS
:
export const isIOS = () => {
let platform = navigator?.userAgent || navigator?.platform || 'unknown'
return /iPhone|iPod|iPad/.test(platform)
}
The result will be true
if is an iPhone
or iPod
or Ipad
or it will be false
otherwise.
You may ask, why do I need to check navigator.userAgent || navigator.platform
, well the reason is simple the second option used to be the default one but now it is deprecated and some browsers will stop supporting this in the future, the first one is more reliable.
You can check here about the deprecation that I mentioned above:
https://developer.mozilla.org/en-US/docs/Web/API/Navigator/platform#:~:text=Deprecated%3A%20This%20feature%20is%20no,be%20kept%20for%20compatibility%20purposes.
Logging the userAgentData
, userAgent
and platform
.
Using the function below, I received these logs:
console.log({
userAgentData: navigator?.userAgentData?.platform,
userAgent: navigator?.userAgent,
platform: navigator?.platform,
})
{
"userAgentData": "",
"userAgent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1",
"platform": "MacIntel"
}
I was testing it on my Macbook and it worked on different browsers and operation systems. So, as you can see navigator?.userAgentData?.platform
will not work at all.
I also didn't receive any errors related to my typescript, even though that I am using React to call this function.
Bonus, isAndroid
If you wondering how to check if is an Android platform, I suggest you don't follow the idea of doing the opposite of isIOS
as:
const isAndroid = !isIOS();
The reason is quite simple, it will not work since desktops will be recognized as an Android platform.
To solve this problem you just need to do this check:
export const isAndroid = () => {
const ua = navigator.userAgent.toLowerCase() + navigator?.platform.toLowerCase();
const isAndroid = ua.indexOf("android") > -1;
return isAndroid;
}
The reason why we are checking navigator.userAgent
plus navigator?.platform
is to support old browsers and the new ones.