Auto detect mobile browser (via user-agent?) [closed]
Asked Answered
P

16

294

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?

Priapus answered 17/6, 2009 at 4:40 Comment(9)
Does iPad count? :)Stoneman
Seva's comment brings up a good question. What does "mobile" really mean today? Does it refer to a "feature phone" that has a browser but not much of one? Does it refer to full featured smart phones where the input method and display resolution are limiting factors? How about tablets that are both easy to interact with and have high resolution displays? How about devices like media centers - they never leave the livingroom but they have similar limitations. A friend at work sent me this. I found it very insightful. slideshare.net/bryanrieger/rethinking-the-mobile-web-by-yiibuPacesetter
But the ipad is a tablet.. and uses safari for default, it is unlikely youd want to count the ipadBewley
@Bewley but on the ipad you still cannot e.g. display flash content or use a javascript-based rich text editor like tinymce.Gemstone
@TJ Ellis really? I thought the ipad2 could handle flash. Thats a good point then, but there are ways around that. Such as HTML5's video & canvas options for a ipad compatible site as safari has HTML5 capabilities.Bewley
@Bewley perhaps ipad2 can? I'm not sure, I don't have one myself, but my boss has an ipad of some kind and I know he cannot view flash...Gemstone
ipad cannot view flash, but thats a different topic, like detect if browser supports flash.Repetend
Just a post from the future, but anyone interested in serving a mobile version of their site may be interested in some articles on "responsive design".Sidell
I'd highly suggest using Conditionizr, you can add your own tests and they have a load of tests available too: conditionizr.com/detectsNectarine
C
91

Yes, reading the User-Agent header will do the trick.

There are some lists out there of known mobile user agents so you don't need to start from scratch. What I did when I had to is to build a database of known user agents and store unknowns as they are detected for revision and then manually figure out what they are. This last thing might be overkill in some cases.

If you want to do it at Apache level, you can create a script which periodically generates a set of rewrite rules checking the user agent (or just once and forget about new user agents, or once a month, whatever suits your case), like

RewriteEngine On

RewriteCond %{HTTP_USER_AGENT} (OneMobileUserAgent|AnotherMobileUserAgent|...)
RewriteRule (.*) mobile/$1

which would move, for example, requests to http://domain/index.html to http://domain/mobile/index.html

If you don't like the approach of having a script recreate a htaccess file periodically, you can write a module which checks the User Agent (I didn't find one already made, but found this particularly appropriate example) and get the user agents from some sites to update them. Then you can complicate the approach as much as you want, but I think in your case the previous approach would be fine.

Consolidate answered 17/6, 2009 at 4:48 Comment(2)
Can this be accomplished at the web server layer (Apache) through some type of .htaccess command - instead of using a scripting language like PHP?Priapus
any idea to set document root by user-agentCoagulase
U
126

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

Uncommunicative answered 7/10, 2009 at 22:54 Comment(7)
This failed on my phone (Samsung u550 using Verizon Wireless).Gardel
@guitar If that's the case then you should send in your UA.Carpathoukraine
Bleh... I really dislike the "code smell" of these solutions. Regex matching using a bunch of 4-character prefixes with no clue regarding where they originally came from... no thanks.Hallucination
That is one knarly regex statement. I agree, the code smell is not good on this one.Gurias
I aso don;t like "Open Source" solutions without License and no indication of updates.Estipulate
There's no way around it though. At some level any type of solution is going to do a regex check on the user agent.Jowl
Given the apparently huge number of browsers that regex tries to detect, and the fact that it has to be constantly updated, I really hope they come up with a simple browser API for this. Or specifically, a way to query if the device will provide an onscreen keyboard, so I can avoid focusing inputs if it will trigger that.Jacklight
C
91

Yes, reading the User-Agent header will do the trick.

There are some lists out there of known mobile user agents so you don't need to start from scratch. What I did when I had to is to build a database of known user agents and store unknowns as they are detected for revision and then manually figure out what they are. This last thing might be overkill in some cases.

If you want to do it at Apache level, you can create a script which periodically generates a set of rewrite rules checking the user agent (or just once and forget about new user agents, or once a month, whatever suits your case), like

RewriteEngine On

RewriteCond %{HTTP_USER_AGENT} (OneMobileUserAgent|AnotherMobileUserAgent|...)
RewriteRule (.*) mobile/$1

which would move, for example, requests to http://domain/index.html to http://domain/mobile/index.html

If you don't like the approach of having a script recreate a htaccess file periodically, you can write a module which checks the User Agent (I didn't find one already made, but found this particularly appropriate example) and get the user agents from some sites to update them. Then you can complicate the approach as much as you want, but I think in your case the previous approach would be fine.

Consolidate answered 17/6, 2009 at 4:48 Comment(2)
Can this be accomplished at the web server layer (Apache) through some type of .htaccess command - instead of using a scripting language like PHP?Priapus
any idea to set document root by user-agentCoagulase
B
33

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.

Bluefield answered 6/11, 2009 at 20:19 Comment(3)
This is a very good idea, I think it's an elegant solution.Bladderwort
+1 this sounds like a pretty sweet idea, but would this affect search engine crawlers?Unitary
This is a misguided idea. Browser extensions that disable javascript are very popular on desktop browsers, so assuming that no javascript means mobile is just plain wrong. Window/viewport/screen resolution has nothing to do with a browser's size, and assuming that low resolution indicates handheld size will make your web app ugly and frustrating to many users. (For example: desktop browsers in non-full-screen windows, large tablets.)Mister
P
31

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.

Proscenium answered 14/4, 2011 at 17:53 Comment(4)
if you want to merge your accounts see here: meta.stackexchange.com/questions/18232/…Hall
This won't work when it comes to tablet (e.g. iPad)Ernaline
Use "mobi" because of Opera Mobile.Held
And you need "Opera Mini" as this is one of the rare browsers not using "mobi" in the User Agent.Held
B
17

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

Brambly answered 21/5, 2010 at 17:46 Comment(3)
It's good, but the statement "works with every major programming/language platform" is a little bold.Jowl
It's also no longer free.Toffee
It is now only available under the pesky AGPL licence, unless you buy it. en.wikipedia.org/wiki/WURFL#License_updateToffee
B
17

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

Beastly answered 26/11, 2011 at 19:3 Comment(3)
I think this is actually the best way to go. Scripts that look at User Agent strings are destined to get out of date. Looking at available screen real estate allows responsive design without any worry of new devices not being detected.Carpathoukraine
This only works for client-side detection. But if you want your server side to behave differently for mobile clients, you'll need to use some other technique.Steven
This fails miserably for desktop browsers that aren't running full-screen. If you choose to do it anyway, please don't waste screen space with enormous fonts and margins, or hide important functionality/information behind drop-down menus. It will make your site/app ugly and frustrating to some of your users.Mister
S
13

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>
Stagger answered 9/11, 2011 at 17:24 Comment(5)
I found this quite helpful.Fianna
You should definitely check out Conditionizr which will handle all this for you! You can add custom tests, fetch them via object tests and having callbacks. They've also got a range of premade tests available: conditionizr.com/detectsNectarine
Elenasys, thank you for useful answer. Although, I can't find any UA matching "windows\sce" in my db.Winstead
This does not work for windows phones.Toft
thank you but Windows phone was not specified...Stagger
O
6

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

Odetteodeum answered 17/6, 2009 at 14:46 Comment(1)
Is Mobile Device Browser still working? I notice that there is a notation about it being offline?...Glissando
E
5
protected void Page_Load(object sender, EventArgs e)
{
    if (Request.Browser.IsMobileDevice == true)
    {
        Response.Redirect("Mobile//home.aspx");
    }
}

This example works in asp.net

Encroach answered 20/7, 2011 at 12:41 Comment(0)
A
5

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
    }

    });
Alvinaalvine answered 1/1, 2013 at 6:14 Comment(1)
For a more manageable solution, you can use Conditionizr which will handle all this for you! You can add custom tests, fetch them via object tests and having callbacks. They've also got a range of premade tests available: conditionizr.com/detectsNectarine
C
4

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/

Cosine answered 14/11, 2010 at 10:56 Comment(1)
Using .match is wrong here, you want to be using .test() which evaluates to a boolean value, it's also much faster than .match() and doesn't return an array. For a more manageable solution to your userAgent testing, you can use Conditionizr which will handle all this for you! You can add custom tests, fetch them via object tests and having callbacks. They've also got a range of premade tests available: conditionizr.com/detectsNectarine
L
3

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
}
Libove answered 18/4, 2011 at 14:19 Comment(1)
What module to use: neilb.org/reviews/user-agent.htmlCosset
G
0

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.

Gage answered 17/6, 2009 at 4:46 Comment(1)
Can this be accomplished at the web server layer (Apache) through some type of .htaccess command - instead of using PHP?Priapus
A
0

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!

Atp answered 9/7, 2010 at 17:7 Comment(0)
R
0

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.

Rifkin answered 15/9, 2011 at 14:37 Comment(0)
S
-1

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

Schach answered 2/11, 2010 at 16:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.