Skip to content Skip to sidebar Skip to footer

Simple Javascript Detect User's Device

I want to add javascript into my template to detect that every time users view my websites with what kind of device (Smartphone, tablet or PC). Currently, I try to do it with javas

Solution 1:

The premise of the question, that browser-sniffing is acceptable, is false. You should never engage in browser sniffing, simply because you cannot confidently accomplish what you set out to accomplish. User Agent Strings are not immutable, and are often times changed by plugins installed on the client machine, or by the client themselves (not uncommon, since bad programmers may lock them out of a site based on their UA-String).

Rather than asking what device the user is one, you should instead be asking what functionality is the device capable of. This brings you to feature detection, where you set out to do X, test to see if the user agent is capable of doing X, and then proceed to do or not do X. For instance:

if ( !!document.createElement("video").canPlayType ) {
  console.log( "HTML5 Video Supported" );
}

This is more reliable than trying to see if the user is on an iPhone, iPad, Windows Tablet, or HTML5 Enabled Browser. You can use tools like Modernizr to perform a lot of these tests for you - over 40 in fact.


Solution 2:

There many mobile devices on the market + each device can have more than one browser installed. I would prefer using some library rather than funding "iPhone" in user agent string (I'm using Android phone with Opera browser myself)

For example:

Both of them are regularly updated with latest mobile devices released and provide you with information which features are supported on given device


Solution 3:

This is how I use javascript to detect iOS devices

<script type="text/javascript">
    var agent = navigator.userAgent.toLowerCase();
    var isiPhone = ((agent.indexOf('iphone'))!=-1)

    if (((agent.indexOf('iphone'))!=-1) {
        document.location = "mobile.aspx?device=iphone";
    }

    if (((agent.indexOf('ipod'))!=-1) {
        document.location = "mobile.aspx?device=ipod";
    }

    if (((agent.indexOf('iPad'))!=-1) {
        document.location = "mobile.aspx?device=ipad";
    }
</script>

Post a Comment for "Simple Javascript Detect User's Device"