Shahruk Khan

home

Detecting Android Devices on the Frontend with Javascript

12 January 2016

I was doing some work for our client Estee Lauder today when I stumbled upon an issue with Android playing YouTube videos. If you try and automatically play the video, a lot of Android devices will give you a black screen with an error message and a loading icon. Your mileage may vary with which Android device you have, but our goal was to create a bug free experience for all Android devices.

This was the code that was not working:

    // Create a YouTube player
    // .. Some Code ..
      events: {

        // On ready, automatically play the video
        'onReady': function(event) {

          event.target.playVideo();
        },
      }

I was looking for a quick snippet of code. I like to keep my code modular and simple whenever possible. In this case, I needed a simple boolean for whether the client was Android or not. A lot of examples showed solutions that took 6 - 8 lines which I felt was unnecessary bloat.

In the end I decided to create a 1 line self invoking anonymous function that checks the user agent string for "android" and returns the evaluation.

Simple, clean, and easy for future developers to work with. Those are the goals I have when writing code.

    // Create a YouTube player
    // .. Some Code ..

      events: {

        // On ready, automatically play the video
        'onReady': function(event) {

          var isAndroid = (function() {
            return (navigator.userAgent.toLowerCase().indexOf('android') > -1);
          })();

          if(!isAndroid) {
            event.target.playVideo();
          }
        },
      }