Home > front end >  How can I reliably determine which mobile platform a user is on via javascript?
How can I reliably determine which mobile platform a user is on via javascript?

Time:03-24

I want to figure out if a user has accessed the application via a browser on Android or iOS. The business wants to show slightly different things for those platforms. I know I could use navigator.platform, but Mozilla says that navigator.platform is deprecated. In 2022, what should I use to feature detect Android and iOS?

CodePudding user response:

The answer you're looking for is probably on this Mozilla page.

CodePudding user response:

According to MDN, the correct method is to use navigator.userAgentData.platform, but the problem with that approach is that it's not currently supported in FireFox, Safari, Android Browser, or Chrome on Android.

The recommended alternative to this [navigator.platform] property is navigator.userAgentData.platform. However, navigator.userAgentData.platform is not yet supported by some major browsers, and the specification which defines it has not yet been adopted by any standards group (specifically, it is not part of any specification published by the W3C or WHATWG).

For now at least, navigator.userAgent seems to be a decent choice. It's currently supported by all major browsers, however the values provided by browser manufacturers may change without notice, so that's something to be aware of.

The specification asks browsers to provide as little information via this field as possible. Never assume that the value of this property will stay the same in future versions of the same browser. Try not to use it at all, or only for current and past versions of a browser. New browsers may start using the same UA, or part of it, as an older browser: you really have no guarantee that the browser agent is indeed the one advertised by this property.

Also keep in mind that users of a browser can change the value of this field if they want (UA spoofing).

https://developer.mozilla.org/en-US/docs/Web/API/Navigator/userAgent

That said, I might approach the problem like this:

const os = (() => {
    if (/windows/i.test(navigator.userAgent)) {
        return "Windows"
    }
    else if (/iphone/i.test(navigator.userAgent)) {
        return "iOS"
    }
    else if (/ipad/i.test(navigator.userAgent)) {
        return "iOS"
    }
    else if (/macintosh/i.test(navigator.userAgent)) {
        return "Mac OS"
    }
    // more user agents to detect...
})();
  • Related