Detect phone vs tablet - javascript

Is there a way to detect if the user is using a tablet or a phone?
As an example a person surfing the web using a tablet (any android tablet with version 3+ and iPad) they would surely like to view the same not stripped down version as a person sitting with a desktop computer. And a phone surfer would surely prefer the stripped down version of the site because its quicker to load and might be easier to navigate with your thumb.
This could be done with checking userAgent oct screen width found here:
What is the best way to detect a mobile device in jQuery?
But the problem comes with a phone like Google Galaxy Nexus which has the same resolution as a tablet but only half the screen size. In my opinion it would be nicer to show the mobile version since the screen is small even though the resolution is high.
Is there a way to detect this or do I have to make a compromise?

I think you're making a fundamentally arbitrary distinction between tablet, phone, or any other web enabled device here. It seems like the physical dimensions of the screen is the metric you want to use to dictate the content you serve.
In this case I would try to implement logic based on values passed by the user agent in the HTTP headers ([mobiforge.com...]) and degrade gracefully to prompting the user if information isn't available.
Your logic might look a bit like this:
If the user agent supplies a physical screen size in HTTP headers
physical dimensions = UA value.
otherwise, if the user agent supplies a resolution and pixel dimensions
physical dimensions = pixel dimensions divided by resolution.
(optionally) otherwise, use client side script to detect resolution and PPI
otherwise, if the user agent string looks like some kind of mobile device (regex)
prompt the user to select.
otherwise
assume a default option.
Update:
My answer is now three years old. It's worth noting that support for responsive design has progressed significantly and its now common to deliver the same content to all devices and rely on css media queries to present the site in a way that is most effective for the device it is being viewed on.

Based on google's suggestion: found here (also referenced by Greg) this is what I have used in projects before.
if (/mobile/i.test(navigator.userAgent) && !/ipad|tablet/i.test(navigator.userAgent)) {
console.log("it's a phone"); // your code here
}
It's maybe not the most elegant solution... but it does the job.

If you're using media queries in theory you could use #media handheld but support is pretty much non-existent.
Simplest way of identifying high res mobile devices would be to look at the DPI of the screen and the device-pixel-ratio (via webkit/mozilla vendor specific tags currently)
#media (-webkit-max-device-pixel-ratio: 2),
(max--moz-device-pixel-ratio: 2),
(min-resolution: 300dpi) {
...
}
edit: window.devicePixelRatio to do the above in JS
There is a nice article here with lots of ideas for identifying mobile devices.
http://davidbcalhoun.com/2010/using-mobile-specific-html-css-javascript

If you are using Cordova I like this:
cordova plugin add uk.co.workingedge.phonegap.plugin.istablet
then anywhere in your code call this:
window.isTablet

Unfortunately, as of now, the only reliable way to distinguish between mobile and tablet is via the user agent string.
I have yet to find a user agent that includes device dimensions.
If you try to calculate the device ppi, they almost all inevitably come out to 96ppi, whether a desktop or a phone.
Search for iPad/iPod/iPhone in the user agent string to detect any Apple device. This will tell you if you have a tablet or phone/iPod from Apple. Fortunately, there are far fewer flavors of i-devices, so it will also be easier to distinguish amongst them.
To identify an Android device, search for "Android" in the user agent string. To determine if it is a tablet or a phone, the phone user agent (for native android browser and chrome) will contain "Mobile Safari", whereas the tablet will only contain "Safari". This method is recommended by Google:
As a solution for mobile sites, our Android engineers recommend to
specifically detect “mobile” in the User-Agent string as well as
“android.”
A fuller description can be found here:
http://googlewebmastercentral.blogspot.com/2011/03/mo-better-to-also-detect-mobile-user.html
Of course this is not ideal, but looks to be the only reliable means. As a warning, from looking at a large sample list of user agent strings (near one hundred), I did see one or two older devices that did not adhere to the "Mobile" vs. "Mobile Safari" distinction properly.

You can use something like Device Atlas to detect these features off the User Agent. The offer an API that you can host yourself, and they also offer a cloud service. Both are premium (paid-for)
Alternatively you can use something like Wurfl which, in my experience, is less accurate.

Why try to guess what the user has when you can ask them? You can use the resolution to guess which sort of device is being used, and ask the user which view they want if it falls into the category of possibly mobile or tablet. If you detect it wrong then it's a nuisance for the user. Asking them once which type of device they have is more convenient in my opinion.

I think WURFL might be something to look at:
http://wurfl.sourceforge.net/help_doc.php
Its a bit more hardcore since its more server-side solution rather than doing it simply via simple media queries (for example your own or using a framework like Foundation CSS) or with pure javascript (adapt.js).
Than can do something like:
$is_wireless = ($requestingDevice->getCapability('is_wireless_device') == 'true');
$is_smarttv = ($requestingDevice->getCapability('is_smarttv') == 'true');
$is_tablet = ($requestingDevice->getCapability('is_tablet') == 'true');
$is_phone = ($requestingDevice->getCapability('can_assign_phone_number') == 'true');
if (!$is_wireless) {
if ($is_smarttv) {
echo "This is a Smart TV";
} else {
echo "This is a Desktop Web Browser";
}
} else {
if ($is_tablet) {
echo "This is a Tablet";
} else if ($is_phone) {
echo "This is a Mobile Phone";
} else {
echo "This is a Mobile Device";
}
}
ref: http://wurfl.sourceforge.net/php_index.php
or in Java:
WURFLHolder wurfl = (WURFLHolder) getServletContext().getAttribute(WURFLHolder.class.getName());
WURFLManager manager = wurfl.getWURFLManager();
Device device = manager.getDeviceForRequest(request);
String x = device.getCapability("is_tablet"); //returns String, not boolean btw
ref: http://wurfl.sourceforge.net/njava_index.php

As many other posters have noted, your are likely going to want to parse the User-Agent request header. For this purpose, I found the ua-parser-js library very helpful.

Related

Is there a correct/recommended way of detecting my UWP app I'm running on a Phone?

Trying out Windows Universal apps with JavaScript I noticed the WinJS.Utilities.isPhone property is no longer available, which makes sense since there would be no reason to ask for that at runtime.
I do want to know just for testing purposes if there is a proper way of detecting the device my app is running in.
EDIT: My question is NOT about detecting a mobile browser. I'm talking about about a brand new Universal Windows App for Window 10 that can run on phones, desktops, tablets, Xbox, HoloLEns, IoT devices et all. WinJS had a property that would tell me whether I was running on the phone or not. That property is now gone. Please don't close this question due to duplicate with "detecting mobile browser". That is NOT what I need.
Caveat: Any form of device detection is fragile due to the dynamic nature of hardware - a new device could come along tomorrow that breaks your app's logic. It is best to use these APIs only for telemetry / analytics rather than to trigger runtime behaviour.
More often than not, what you really want to know is some attribute of the device or the app that is not inherently tied to the device family (does this device support SystemTray API? Is there a keyboard attached? Is the window more than 500px wide? etc.).
That said, in Windows 10 you can query the DeviceFamily via AnalyticsInfo.VersionInfo.DeviceFamily and it will tell you things like "Mobile" or "Desktop" or "Xbox" etc. (where "Mobile" could be any class of device - phone, tablet, etc.). There is also a property DeviceForm that might be helpful, but again you can't really rely on it at runtime to deterministically say you're running on "a phone."
So basically the answer is "you can use these APIs for telemetry but don't hard-code any values into your app lest it break when a new device arrives on the market." At the very least, always make sure you handle the case where the returned value isn't one you know about a-priori.
You can also check out the following links
http://www.abeautifulsite.net/detecting-mobile-devices-with-javascript/
http://www.sitepoint.com/detect-mobile-devices-jquery/
and of course a similar post here on stackoverflow with a good answer
Detecting a mobile browser
And talking about Windows 10, extracting from Winjs Github repo, here is the answer.
https://github.com/winjs/winjs/issues/601#issuecomment-87137485
There are numerous JS libs to detect which platform/device is used.
I personally love using this lib: https://github.com/kaimallea/isMobile
You will then be able to detect mobile device in such a way:
isMobile.apple.tablet
isMobile.android.phone
and so on.
In case you have an idea to implement such lib yourself, keep in mind that it takes some efforts to keep it up-to-date, because ways of detecting mobile device may change over time.
In general, common way of detecting user device is checking query headers.
Keep in mind, though, that you can't absolutely rely on this information - headers may be easily modified. Google for User Agent for more info.
So "omitting auth process for users with phones" is extremely bad idea

Laptop with touchscreen UserAgent

I am investigating how to differentiate tablets with Windows 8 and other devices. According to this doc http://msdn.microsoft.com/en-us/library/ie/hh869301%28v=vs.85%29.aspx there should be "Touch" token in UserAgent in tablets with Windows.
But I am worried, will laptops with touchscreen also have this token in UserAgent. Unfortunately, do not have such device and test in myself.
Can someone please confirm that this "Touch" token is used in Internet Explorer for tablets and mobile phones only?
OK so I think you created a diversion for some here, you are not trying to detect touch per se as much as you want to detect if a device is a tablet or desktop. As I stated earlier in my comment you should not use any user agent string to do feature detection, ever. Detect the features directly.
FWIW here is how I detect touch support in DeepTissue :
this.touchType = window.navigator.pointerEnabled ? "pointer" :
"ontouchstart" in window ? "touch" : "mouse";
Notice how I detect pointer events first then fall back to other input modality APIs?
On to what I think the essence of your question really is, how can I design an interface that is optimized for legacy desktops and modern touch enabled devices? This is where you need to tap that artistic part of your mind and meld it with valuable UX research by folks like Jacob Nielson on what works and what does not work. As you have seen Microsoft, Google and Apple all struggle with this same question it is not easy to answer. My advice, based on lots of experience, is to create a simple, responsive UI and grow from that. Start mobile first and design up from there. Remember, if it works with fat fingers then it will work with a mouse pointer. Touch is a direct input modality, where a mouse in indirect, so the experience is slightly different.
Make all your data actionable. This means instead of a small touch target with an anchor wrapped around text make the anchor wrap around the product photo. Make sure there is enough padding within the anchor to make the touch targets easier to hit and make sure there are margins between adjacent targets to reduce errors.
This is not an easy question to answer with an exact science because each application has its own character or personality. Users vary, etc. But one thing is for sure touch is quickly replacing non-touch devices and you need to account for that in any application design.
You cannot guarantee that any token, let alone the touch token, will be used only for Windows tablets or phones. Period. For example, the UA string can be modified by third party controls, group policy, and even the end-user. It's unpredictable, at best.
I know of no standard that dictates (normatively) the contents of the user-agent string. Various browsers and user agents have copied elements of other user agent strings for their own purposes to ensure that their user agent receives content. Indeed, the IE team is already on record as saying that the user-agent string for Windows 10 is designed to ensure the delivery of content, rather than the identification of the browser.
Because of this, reliance on the user-agent string is no longer considered a "good" practice, let alone a best one. This is only one reason why Microsoft's content has been advocating feature detection and other practices since the release of IE9. (Other resources have been deprecating the user-agent string for much longer.)
You haven't said why you need to differentiate one manufacturer's tablets and phones from another or what changes you hope to offer such differentiated devices. As a result, it's difficult (if not impossible) to recommend a more effective approach.
If you are trying to create an app that works only on these devices, then the web platform is probably not the one to use. If you're looking to provide content or functionality specific to these devices, the Windows Store platform (or the .NET framework) may be more appropriate. If you're looking for a way to exclude these devices from your offerings, then you may wish to consider an Android or iOS specific platform instead.
The web platform is meant, in part, to be device agnostic, to enable a consistent--and predictable--set of functionality across a wide set of devices, form factors, and operating systems.
Hope this helps...
-- Lance
Mozilla says... ish.
var isTouch = 'ontouchstart' in window ||
navigator.maxTouchPoints > 0 ||
navigator.msMaxTouchPoints > 0;

Detecting "dumb" phones using jQuery/JavaScript?

I can't figure out how to detect a "dumb" phone browser using jQuery/JavaScript. I have a desktop/tablet, a smartphone, and a dumbphone version of my website. The smartphone version of the site is too heavy and slow for dumb phones so I want to redirect them to the "lite" version instead.
A good example of this would be Facebook. When I open Facebook on a dumb phone browser, the users get redirected to hte lite version. How do I do that same behavior?
NOTE: I am using JavaScript and not PHP beacuse of platform constraints. (It is on Tumblr.)
In your javascript you will need to detect the user agent variable (this is what each browser uses to identify itself).
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
// Redirect code goes here
window.location = "someplace.com";
}
Essentially you will have to manually enter the types to test for in this and have an if/else statement for each case. (See http://www.w3schools.com/jsref/prop_nav_useragent.asp and http://useragentstring.com/pages/useragentstring.php)
Another good way would be check if certain features are present in the browser, like the http://modernizr.com/ library does. This might be better performance wise and you won't have to update the user-agent string every-time you find a "dumbphone".

Can you detect whether a device has phone capabilities (e.g. it can make voice calls/SMS) with JavaScript?

Is there any way to detect whether a mobile device is capable of making voice calls / SMS messages?
This is important when applying tel: and sms: links in a web page. It is not enough to merely detect mobile, since tablets can't make calls, iTouch can't make calls, etc.
I'm not interested in mobile detection hacks using device size, UA string detection, etc. I want to use feature detection to determine if the device is capable of voice calls / SMS text messaging. I'd love a universal solution, but am mainly interested in iOS / Android.
I havent seen an obvious way to see that sms: and tel: links get special treatment.
Update: #janogosteve below has confirmed there is currently no reliable feature detect. This looks undetectable.
Here's a comprehensive way to check this feature detect. (Read jangosteve comment below!)
make a test page with two of those links and a regular http link
grab the elements and then traverse all their properties, copy it all over to an object..
also getComputedStyle info for a bunch of details on them and throw that into an object as well
JSON.stringify( that stuff so you can deal with it later on)
Do the above on an iOS device and in desktop Safari/Chrome
Then JSON.parse them back into objects... and use https://github.com/NV/objectDiff.js to see if you can spot any differences at all.
A new plot twist in this problem (as of Feb 2015) is that many desktop browsers now support click-to-call, however they won't auto-detect phone numbers.
So the nifty tricks floating around for sniffing out phone number auto-detection or touch capability, are now obsolete.
Mac OSX since Yosemite 10.9.2 has supported click-to-call with Facetime audio, and Windows 8 / IE11 does the same using Skype. Not sure about Chrome OS (Hangouts?). iPads use Facetime audio calls.
It looks like all web browsers from now onwards will support click-to-call. The question is really about how to prevent older browsers and desktop OS users from getting an error when clicking a tel: link.
I made a Javascript library to attempt to detect older desktop OS users that are before tel: link support, but it proved very problematic and complicated.
Right now my approach is either:
A) Leave it as a link for all users. Users without a call-capable browser will just have to suffer
B) Use a media query to hide the link styling for only desktop browser widths, assuming that most desktop users aren't going to be
making calls from their desktop PC anyhow.
C) Skip the <a> tag and desktops altogether and let auto-detection do it's link magic on mobile devices
I'm not crazy about any of these solutions, but I'm opting for B until the browser support landscape changes in the future. That way I have control over the <a> tag, a desktop user can still click the phone # if they really want to, and I can swap easily in the future.

How do I tell whether a browser is on a touchscreen device with JavaScript?

I know this is a bit of perennial question, but here goes: I want to know whether the device my site is being accessed with is a touchscreen. That means phones and iPads, of course, which are individually detectable, but also other touchscreens that may well be running flavors of Windows. Any chance of determining the presence or absence of a mouse on those?
Let's say I'm willing to use a large JavaScript library like Modernizr. Will that help any?
You might want to look into MobileESP. Not touchscreens only, but it at least gives you some detection capabilities. From their page:
The MobileESP project seeks to provide
web site developers an easy-to-use and
lightweight API for detecting whether
visitors are using a mobile device,
and if so, what kind. The APIs provide
simple boolean results for popular
individual device OS categories (such
as iPhone, BlackBerry, Symbian S60,
and Windows Mobile), device
capabilities (e.g., J2ME), and broad
classes of devices, such as "iPhone
Tier" (iPhone/Android/WebOS) and
smartphones.
Try http://wurfl.sourceforge.net/ for device capabilities.

Categories

Resources