JavaScript User Agent mobile/tablet os detection
When developing websites and web apps for mobile devices (smartphones and tablets) you need to know the user's device, and in some cases even the OS version to appropriately render content and perform other tasks. For most cases you can use Modernizr which is a great tool for feature detection in browsers. But when you need to minimize load, you're often forced to use custom solutions.
This used to be pretty straightforward, until the latest User-Agent update in Windows Phone 8.1 Update
The new User Agent string for Windows Phone 8.1 Update Internet Explorer now looks like this:
Mozilla/5.0 (Windows Phone 8.1; ARM; Trident/7.0; Touch; rv:11; IEMobile/11.0) like Android 4.1.2; compatible) like iPhone OS 7_0_3 Mac OS X WebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.99 Mobile Safari /537.36
What this means is that using conventional detection would register the latest Windows Phone OS as an Android and iOS device as well as a Windows Phone. To make matters worse, IE 10 is in many cases behaving differently than IE 11 on mobile devices, so we have to filter it out. The same goes for Windows Phone 8.1 (pre update) versus the Update - again, different behaviour in browsers. You can look at the code below to see, how to identify different OS and browsers. We need almost no additional differentiation on iOS and Android, while we have to map almost every single update to IE separately, because each iteration has some major behavioural changes.
// USER AGENT IDENTIFICATION var ua = navigator.userAgent.toLowerCase(); var platform = ""; var iPhone = ua.indexOf("iphone") > -1; var iPod = ua.indexOf("ipod") > -1; var iPad = ua.indexOf("ipad") > -1; var ios_43 = ua.indexOf("os 4_3") > -1; var isAndroid = ua.indexOf("android") > -1; var msie = ua.indexOf("msie") > -1 || ua.indexOf("iemobile") > -1 || ua.indexOf("wpdesktop") > -1; var msie10 = ua.indexOf("msie 10") > -1; var msie81 = ua.indexOf("windows phone 8.1") > -1; var msie81Update = false; if (msie && isAndroid && iPhone) { msie81Update = true; }
Now, because of the latest update, this doesn't suffice for correct identification. When checking for Android or iOS devices we always have to make sure, we're not targeting IE 11 WP 8.1 Update aswell, since it's mimicking the Android and iOS User Agent:
if (isAndroid && !msie81Update) { // Android } if (iPhone && !msie81Update) { // iPhone } if (iPad && !msie81Update) { // iPad } ...
And it looks like Microsoft is going to persist this User Agent faking in the future.












