[html] Auto detect mobile browser (via user-agent?)

How can I detect if a user is viewing my web site from a mobile web browser so that I can then auto detect and display the appropriate version of my web site?

This question is related to html windows-mobile browser user-agent

The answer is


I put this demo with scripts and examples included together:

http://www.mlynn.org/2010/06/mobile-device-detection-and-redirection-with-php/

This example utilizes php functions for user agent detection and offers the additional benefit of permitting users to state a preference for a version of the site which would not typically be the default based on their browser or device type. This is done with cookies (maintained using php on the server-side as opposed to javascript.)

Be sure to check out the download link in the article for the examples.

Hope you enjoy!


Just a thought but what if you worked this problem from the opposite direction? Rather than determining which browsers are mobile why not determine which browsers are not? Then code your site to default to the mobile version and redirect to the standard version. There are two basic possibilities when looking at a mobile browser. Either it has javascript support or it doesn't. So if the browser does not have javascript support it will default to the mobile version. If it does have JavaScript support, check the screen size. Anything below a certain size will likely also be a mobile browser. Anything larger will get redirected to your standard layout. Then all you need to do is determine if the user with JavaScript disabled is mobile or not.
According to the W3C the number of users with JavaScript disabled was about 5% and of those users most have turned it off which implies that they actually know what they are doing with a browser. Are they a large part of your audience? If not then don't worry about them. If so, whats the worst case scenario? You have those users browsing the mobile version of your site, and that's a good thing.


My favorite Mobile Browser Detection mechanism is WURFL. It's updated frequently and it works with every major programming/language platform.


Here's how I do it in JavaScript:

function isMobile() {
  var index = navigator.appVersion.indexOf("Mobile");
  return (index > -1);
}

See an example at www.tablemaker.net/test/mobile.html where it triples the font size on mobile phones.


There are open source scripts on Detect Mobile Browser that do this in Apache, ASP, ColdFusion, JavaScript and PHP.


Have you considered using css3 media queries? In most cases you can apply some css styles specifically for the targeted device without having to create a separate mobile version of the site.

@media screen and (max-width:1025px) {
   #content {
     width: 100%;
   }
}

You can set the width to whatever you want, but 1025 will catch the iPad landscape view.

You'll also want to add the following meta tag to your head:

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

Check out this article over at HTML5 Rocks for some good examples


The Mobile Device Browser File is a great way to detect mobile (and other) broswers for ASP.NET projects: http://mdbf.codeplex.com/


You haven't said what language you're using. If it's Perl then it's trivial:

use CGI::Info;

my $info = CGI::Info->new();

if($info->is_mobile()) {
   # Add mobile stuff
}

unless($info->is_mobile()) {
   # Don't do some things on a mobile
}

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.Browser.IsMobileDevice == true)
    {
        Response.Redirect("Mobile//home.aspx");
    }
}

This example works in asp.net


MobileESP has PHP, Java, APS.NET (C#), Ruby and JavaScript hooks. it has also the Apache 2 licence, so free for commercial use. Key thing for me is it only identifies browsers and platforms not screen sizes and other metrics, which keeps it nice an small.


You can detect mobile clients simply through navigator.userAgent , and load alternate scripts based on the detected client type as:

 $(document).ready(function(e) {

        if(navigator.userAgent.match(/Android/i)
          || navigator.userAgent.match(/webOS/i)
          || navigator.userAgent.match(/iPhone/i)
          || navigator.userAgent.match(/iPad/i)
          || navigator.userAgent.match(/iPod/i)
          || navigator.userAgent.match(/BlackBerry/i)
          || navigator.userAgent.match(/Windows Phone/i)) {

         //write code for your mobile clients here.

          var jsScript = document.createElement("script");
          jsScript.setAttribute("type", "text/javascript");
          jsScript.setAttribute("src", "js/alternate_js_file.js");
          document.getElementsByTagName("head")[0].appendChild(jsScript );

          var cssScript = document.createElement("link");
          cssScript.setAttribute("rel", "stylesheet");
          cssScript.setAttribute("type", "text/css");
          cssScript.setAttribute("href", "css/alternate_css_file.css");
          document.getElementsByTagName("head")[0].appendChild(cssScript); 

    }
    else{
         // write code for your desktop clients here
    }

    });

Yes user-agent is used to detect mobile browsers. There are lots of free scripts available to check this. Here is one such php code which will help you redirect mobile users to different website.


for ANDROID , IPHONE, IPAD, BLACKBERRY, PALM, WINDOWS CE, PALM

 <script language="javascript"> <!--
     var mobile = (/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));
              if (mobile) {
                  alert("MOBILE DEVICE DETECTED");
                  document.write("<b>------------------------------------------<br>")
                  document.write("<b>" + navigator.userAgent + "<br>")
                  document.write("<b>------------------------------------------<br>")
                  var userAgent = navigator.userAgent.toLowerCase();
                  if ((userAgent.search("android") > -1) && (userAgent.search("mobile") > -1))
                         document.write("<b> ANDROID MOBILE <br>")
                   else if ((userAgent.search("android") > -1) && !(userAgent.search("mobile") > -1))
                       document.write("<b> ANDROID TABLET <br>")
                   else if ((userAgent.search("blackberry") > -1))
                       document.write("<b> BLACKBERRY DEVICE <br>")
                   else if ((userAgent.search("iphone") > -1))
                       document.write("<b> IPHONE DEVICE <br>")              
                   else if ((userAgent.search("ipod") > -1))
                       document.write("<b> IPOD DEVICE <br>")
               else if ((userAgent.search("ipad") > -1))
                       document.write("<b> IPAD DEVICE <br>")
                       else
                   document.write("<b> UNKNOWN DEVICE <br>")
              }
              else
                  alert("NO MOBILE DEVICE DETECTED"); //--> </script>

You can check the User-Agent string. In JavaScript, that's really easy, it's just a property of the navigator object.

var useragent = navigator.userAgent;

You can check if the device if iPhone or Blackberry in JS with something like

var isIphone = !!agent.match(/iPhone/i),
    isBlackberry = !!agent.match(/blackberry/i);

if isIphone is true you are accessing the site from an Iphone, if isBlackBerry you are accessing the site from a Blackberry.

You can use "UserAgent Switcher" plugin for firefox to test that.

If you are also interested, it may be worth it checking out my script "redirection_mobile.js" hosted on github here https://github.com/sebarmeli/JS-Redirection-Mobile-Site and you can read more details in one of my article here:

http://blog.sebarmeli.com/2010/11/02/how-to-redirect-your-site-to-a-mobile-version-through-javascript/


There's a brand new solution using Zend Framework. Start from the link to Zend_HTTP_UserAgent:

http://framework.zend.com/manual/en/zend.http.html


Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to windows-mobile

How to connect a Windows Mobile PDA to Windows 10 Auto detect mobile browser (via user-agent?)

Examples related to browser

How to force reloading a page when using browser back button? How do we download a blob url video How to prevent a browser from storing passwords How to Identify Microsoft Edge browser via CSS? Edit and replay XHR chrome/firefox etc? Communication between tabs or windows How do I render a Word document (.doc, .docx) in the browser using JavaScript? "Proxy server connection failed" in google chrome Chrome - ERR_CACHE_MISS How to check View Source in Mobile Browsers (Both Android && Feature Phone)

Examples related to user-agent

Change user-agent for Selenium web-driver How to use curl to get a GET request exactly same as using Chrome? How to use Python requests to fake a browser visit a.k.a and generate User Agent? Get operating system info Sites not accepting wget user agent header How does HTTP_USER_AGENT work? What is the iOS 6 user agent string? Detect IE version (prior to v9) in JavaScript How to get user agent in PHP How to find the operating system version using JavaScript?