I need to change out some buttons and text on a mobile website depending on whether the user is viewing it on an Android or iOS browser. Is there a reliable way to perform the check?
On your device, go to the Home screen (the one with all the icons), and tap on the Settings icon. Scroll down and tap on About phone or About tablet. Some information will appear. If one of the lines of information says Android with a version number, you have an Android device.
Here's how you can check whether someone on your website or app is using a mobile iOS device in JavaScript: const ios = () => { if (typeof window === `undefined` || typeof navigator === `undefined`) return false; return /iPhone|iPad|iPod/i. test(navigator.
var isMobile = { Windows: function() { return /IEMobile/i.test(navigator.userAgent); }, Android: function() { return /Android/i.test(navigator.userAgent); }, BlackBerry: function() { return /BlackBerry/i.test(navigator.userAgent); }, iOS: function() { return /iPhone|iPad|iPod/i.test(navigator.userAgent); }, any: function() { return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Windows()); } };
I would use the navigator.useragent
property to get the useragent-string, parse it, and detect the OS.
Here is one example of how you can do it.
Update:
Due to the popularity of this question, I thought I would add some additional information to my answer.
In general, browser sniffing is almost never the best way to go. Why? Well, there are many reasons, but here are two good ones:
With that said, if you really really need to use browser/OS detection, then don't reinvent the wheel, and don't try to do it on your own - you will be in for a world of pain and obscure caveats! I would suggest you use a library like WhichBrowser, that will provide you with a handy JavaScript object containing information about the os, browser, rendering engine and device.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With