Friday, September 6, 2013

Javascript to Sniff Android Based Browsers


Updated on 7th of February, 2014: The is_touch_device() function in the following is no longer working. Please check out my latest is_touch_device() function that works in the latest Chrome browser (Nevertheless, the rest of the codes are still working. Just replace the latest is_touch_device() function will do):

http://webtrick101.blogspot.com/2014/02/detecting-browsers-touch-capability.html



Using Javascript to sniff out Android based broswer is tough as the list of Android devices is very lengthy. Here's my Javascript way of performing the Android sniffing task.

<script>

function is_touch_device() {
 try {
  document.createEvent("TouchEvent");
  return true;
 }
 catch (e) {
  return false;
 }
}

var ie = (navigator.userAgent.indexOf("MSIE") != -1);
var ipad = (navigator.userAgent.indexOf("iPad") != -1);
var iphone = (navigator.userAgent.indexOf("iPhone") != -1);
var bb = (navigator.userAgent.indexOf("BlackBerry") != -1);
var touch = is_touch_device();
var android = touch && !ipad && !iphone && !bb && !ie;

if (android) {
 alert("Hello Droid!");
}

</script>


The logic? A touch capable device which is not either iPad, iPhone, Blackberry, or Windows 8 (touch screen), chance is very high that it is an Android device. But the trend will keep on changing. This should be still good for now.

No comments:

Post a Comment