Target Android Devices with JavaScript

Android Mini Collectibles - Worker front

Having recently created an Android app and an accompanying website to match, I wanted to know how to detect an android device through the site using JavaScript. On the site a download button was created and depending on the device would either say, ‘Download .APK’ or ‘Install App’. I thought this was a clever idea to adapt the site based on what would happen after you download the APK.

The JavaScript snippet is simple enough to work with:

var ua = navigator.userAgent.toLowerCase();

if ( ua.indexOf('android') > -1 )
    // This is an Android Device
    // ... so do something here.

It just grabs the user-agent string and searches through it for ‘android’ using indexof(). It then returns -1 if it’s not there or any number higher if it is there.

This code is based on a more informative blog post by David Walsh which is worth a read.