What Are Available Solutions of a Browser/Mobile Phone Detection

What are available solutions of a browser / mobile phone detection

Changes:

  • 06.03.2013 - Addad a few comments inside a WURFL chapter

Intro :

There are few available solutions but I will only name open-source ones, at least solutions mostly used with a jQuery/jQuery Mobile. Also be warned, this topic has the potential to start a war. On one side we have a proponents of server side detection with their community maintained databases and on the other side we have client side advocates with their browser sniffing.

Server side:

WURFL -

Created in 2002, WURFL (Wireless Universal Resource FiLe), is a
popular open-source framework to solve the device-fragmentation
problem for mobile Web developers and other stakeholders in the mobile
ecosystem. WURFL has been and still is the de facto standard
device-description repository adopted by mobile developers. WURFL is
open source (AGPL v3) and a trademark of ScientiaMobile.

Good :

Very detailed detection, you would probably get more data then is really needed.

Good platform support, api's are available for Java, PHP and .Net.

Bad :

Not always up to date, heavy dependency on community

In case of iPhone there's no way of knowing an iOS version, so media type queries to detect pixel ratios.

Fee only for a non commercial usage, older version are still free for commercial usage but they can only use database updated up to WURFL EULA changes.

  • It can be found here: http://wurfl.sourceforge.net/apis.php

PHP example :

<?php
// Include the configuration file
include_once './inc/wurfl_config_standard.php';

$wurflInfo = $wurflManager->getWURFLInfo();

if (isset($_GET['ua']) && trim($_GET['ua'])) {
$ua = $_GET['ua'];
$requestingDevice = $wurflManager->getDeviceForUserAgent($_GET['ua']);
} else {
$ua = $_SERVER['HTTP_USER_AGENT'];
// This line detects the visiting device by looking at its HTTP Request ($_SERVER)
$requestingDevice = $wurflManager->getDeviceForHttpRequest($_SERVER);
}
?>
<html>
<head>
<title>WURFL PHP API Example</title>
</head>
<body>
<h3>WURFL XML INFO</h3>
<ul>
<li><h4>VERSION: <?php echo $wurflInfo->version; ?> </h4></li>
</ul>
<div id="content">
User Agent: <b> <?php echo htmlspecialchars($ua); ?> </b>
<ul>
<li>ID: <?php echo $requestingDevice->id; ?> </li>
<li>Brand Name: <?php echo $requestingDevice->getCapability('brand_name'); ?> </li>
<li>Model Name: <?php echo $requestingDevice->getCapability('model_name'); ?> </li>
<li>Marketing Name: <?php echo $requestingDevice->getCapability('marketing_name'); ?> </li>
<li>Preferred Markup: <?php echo $requestingDevice->getCapability('preferred_markup'); ?> </li>
<li>Resolution Width: <?php echo $requestingDevice->getCapability('resolution_width'); ?> </li>
<li>Resolution Height: <?php echo $requestingDevice->getCapability('resolution_height'); ?> </li>
</ul>
<p><b>Query WURFL by providing the user agent:</b></p>
<form method="get" action="index.php">
<div>User Agent: <input type="text" name="ua" size="100" value="<?php echo isset($_GET['ua'])? htmlspecialchars($_GET['ua']): ''; ?>" />
<input type="submit" /></div>
</form>
</div>
</body>
</html>

If you want to customize this code, change configuration parameters inside a wurfl_config_standard.php file.


Modernizr - Server -

Modernizr is a great way to find out about your user's browser
capabilities. However, you can only access its API on the browser
itself, which means you can't easily benefit from knowing about
browser capabilities in your server logic. The modernizr-server
library is a way to bring Modernizr browser data to your server
scripting environment.

Good :

Like WURFL very detailed detection, but we need to take into consideration that it is build with a different purpose the WURFL.

Bad :

Only supported on PHP, but sometimes this will be enough.

Example :

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Modernizr Server Example</title>
</head>
<body>
<?php
include('modernizr-server.php');

print 'The server knows:';
foreach($modernizr as $feature=>$value) {
print "<br/> $feature: "; print_r($value);
}
?>
</body>
</html>
  • It can be found here: https://github.com/jamesgpearce/modernizr-server

Client side:

Modernizer -

aking advantage of cool new web technologies is great fun, until you
have to support browsers that lag behind. Modernizr makes it easy for
you to write conditional JavaScript and CSS to handle each situation,
whether a browser supports a feature or not. It’s perfect for doing
progressive enhancement easily.

Good :

Only client side, server side component don't exist

Fast but still large for a javascript framework with its 12kb. Because of its modularity it can become smaller, depending on your needs.

Bad :

Can do only so much, less info then server side detection.

Modernizr itself is a great way to find out about your user’s browser capabilities. However, you can only access its API on the browser itself, which means you can’t easily benefit from knowing about browser capabilities in your server logic.

  • It can be found here: http://modernizr.com/

Example :

    <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Modernizr Example</title>
<script src="modernizr.min.js"></script>
</head>
<body>
<script>
if (Modernizr.canvas) {
// supported
} else {
// no native canvas support available :(
}
</script>
</body>
</html>

JavaScript based browser sniffing

It is arguable that this may be (academically) the worst possible way
to detect mobile but it does have its virtues.

Good :

Simple

Bad :

Where to begin

Example :

<script type="text/javascript">     
var agent = navigator.userAgent;
var isWebkit = (agent.indexOf("AppleWebKit") > 0);
var isIPad = (agent.indexOf("iPad") > 0);
var isIOS = (agent.indexOf("iPhone") > 0 || agent.indexOf("iPod") > 0);
var isAndroid = (agent.indexOf("Android") > 0);
var isNewBlackBerry = (agent.indexOf("AppleWebKit") > 0 && agent.indexOf("BlackBerry") > 0);
var isWebOS = (agent.indexOf("webOS") > 0);
var isWindowsMobile = (agent.indexOf("IEMobile") > 0);
var isSmallScreen = (screen.width < 767 || (isAndroid && screen.width < 1000));
var isUnknownMobile = (isWebkit && isSmallScreen);
var isMobile = (isIOS || isAndroid || isNewBlackBerry || isWebOS || isWindowsMobile || isUnknownMobile);
var isTablet = (isIPad || (isMobile && !isSmallScreen));

if ( isMobile && isSmallScreen && document.cookie.indexOf( "mobileFullSiteClicked=") < 0 ) mobileRedirect();
</script>

Detecting a mobile browser

Using Regex (from detectmobilebrowsers.com):

Here's a function that uses an insanely long and comprehensive regex which returns a true or false value depending on whether or not the user is browsing with a mobile.

window.mobileCheck = function() {
let check = false;
(function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true;})(navigator.userAgent||navigator.vendor||window.opera);
return check;
};

For those wishing to include tablets in this test (though arguably, you shouldn't), you can use the following function:

window.mobileAndTabletCheck = function() {
let check = false;
(function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true;})(navigator.userAgent||navigator.vendor||window.opera);
return check;
};


Using navigator.userAgentData

You may also use navigator.userAgentData.mobile, but userAgentData is still experimental, so it is not recommended for use in production.

const isMobile = navigator.userAgentData.mobile; //resolves true/false

Compatibility chart for userAgentData



The Original Answer

You can do this by simply running through a list of devices and checking if the useragent matches anything like so:

  function detectMob() {
const toMatch = [
/Android/i,
/webOS/i,
/iPhone/i,
/iPad/i,
/iPod/i,
/BlackBerry/i,
/Windows Phone/i
];

return toMatch.some((toMatchItem) => {
return navigator.userAgent.match(toMatchItem);
});
}

However since you believe that this method is unreliable, You could assume that any device that had a resolution of 800x600 or less was a mobile device too, narrowing your target even more (although these days many mobile devices have much greater resolutions than this)

i.e

  function detectMob() {
return ( ( window.innerWidth <= 800 ) && ( window.innerHeight <= 600 ) );
}

Reference:

  • Detecting Browser and Devices with javascript

mobile browser detection

Have a look at the free add-ons MX Mobile Device Detect and Mobile.

Detect if a browser in a mobile device (iOS/Android phone/tablet) is used

Update (June 2016): I now try to support touch and mouse input on every resolution, since the device landscape is slowly blurring the lines between what things are and aren't touch devices. iPad Pros are touch-only with the resolution of a 13" laptop. Windows laptops now frequently come with touch screens.

Other similar SO answers (see other answer on this question) might have different ways to try to figure out what sort of device the user is using, but none of them are fool-proof. I encourage you to check those answers out if you absolutely need to try to determine the device.


iPhones, for one, ignore the handheld query (Source). And I wouldn't be surprised if other smartphones do, too, for similar reasons.

The current best way that I use to detect a mobile device is to know its width and use the corresponding media query to catch it. That link there lists some popular ones. A quick Google search would yield you any others you might need, I'm sure.

For more iPhone-specific ones (such as Retina display), check out that first link I posted.

Standard way to detect mobile browsers in a web application based on the http request

Wouldn't the standard way be to check the user agent? Here's a database of user agents you can use to detect mobile browsers.

Android Phone Browser Detection

Looking at that user agent, I'd have to say that, that would be extremely difficult to differentiate from a non-handheld device.

The problem with browser detection is that it's obviously easy to tweak the user agent string, and thus you never really know if what the server is telling you is honest or not.

You have two options in this case:

  • You can check every single header the phone sends and maybe see if there is one that could make it unique

  • Or find some type of work-around by testing page load time etc..., As a whimsical example, browsers on handheld devices usually render pages a bit slower than their desktop counterparts, so after testing every possible mobile device with something like:

-

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
// some code..
}

You can see if a page with nothing else but a simple script is not loading in it's ideal time.

You get the point.

Also, try going here and see if it can detect you: http://detectmobilebrowsers.com/



Related Topics



Leave a reply



Submit