Pages

Thursday, August 22, 2013

How to detect client device using JavaScript

 Device detection is very important for web application. Sometimes there is different version of same website compatible for different device.

For example, think about one big e-commerce application where lots of information is there in home page. The organization may take decision that when people will browse from computer with high speed of internet then full website will get display and when people from different device (like mobile phone ,PDA etc  ) will browse it will redirect them to customized version of their website, where full features may not available.

Using JavaScript we can check which type of device client is using to browse our application.


<%@
Page Language="C#" AutoEventWireup="true" CodeBehind="CheckMobile.aspx.cs" Inherits="ASP.NET.CheckMobile"
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" language ="javascript">

        functionCheck()
         {
            if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|vodafone|o2|poc ket|kindle|mobile|pda|psp|treo)/i))||     
(navigator.userAgent.match(/iPod/i)) ||          
(navigator.userAgent.match(/operamini/i)) ||
                (navigator.userAgent.match(/blackberry/i))||
                (navigator.userAgent.match(/(palmos|palm|hiptop|avantgo|plucker|xiino|blazer|elaine)/i))
||(navigator.userAgent.match(/(windowsce; ppc;|windows ce;
smartphone;|windows ce;iemobile)/i)) ||
            (navigator.userAgent.match(/android/i)))
{

                 alert("Deviceis mobile ");
               }
             else{
                 alert("Device is computer");
             }
       }

    </script>

</head>
<body onload="Check();">
    <form id="form1" runat="server">
    <div>
    </div>
    </form>
</body>
</html>

The code is very simple and self descriptive. If you know navigator object of JavaScript you can easily understand. Actually navigator property contains information of user agent and user agent is nothing but browser. We are using pattern matching technique to detect device type like below   
 (navigator.userAgent.match(/iPhone/i))
By testing the above code on a computer, we will see the following output .


No comments:

Post a Comment