How to detect a mobile device using JavaScript?

I was asked to create the actual HTML / JavaScript page to simulate the detection of mobile devices (iPhone / iPad / Android) using JavaScript code. This will then lead the user to another screen that asks for their email address.

+71
javascript html mobile device
Jul 12 '11 at 15:37
source share
21 answers

I know that this answer comes in 3 years, but none of the other answers are really 100% correct. If you want to determine whether the user is in ANY form of a mobile device (Android, iOS, BlackBerry, Windows Phone, Kindle, etc.), you can use the following code:

if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent)) { // Take the user to a different screen here. } 
+73
Oct 26 '14 at 20:59
source share

You will find the user agent string of the requesting browsers, and then decide based on what it is if it comes from a mobile browser or not. This device is not perfect and will never be due to the fact that user agents are not standardized for mobile devices (at least as far as I know).

This site will help you create the code: http://www.hand-interactive.com/resources/detect-mobile-javascript.htm

An example :

You can get the user agent in javascript by doing the following:

 var uagent = navigator.userAgent.toLowerCase(); 

And then do the check in the same format as this (just using the iPhone as an example, but others should be a little different)

 function DetectIphone() { if (uagent.search("iphone") > -1) alert('true'); else alert('false'); } 

Edit

You would create a simple HTML page, for example:

 <html> <head> <title>Mobile Detection</title> </head> <body> <input type="button" OnClick="DetectIphone()" value="Am I an Iphone?" /> </body> </html> <script> function DetectIphone() { var uagent = navigator.userAgent.toLowerCase(); if (uagent.search("iphone") > -1) alert('true'); else alert('false'); } </script> 
+26
Jul 12 '11 at 15:41
source share

A fairly simple solution is to check the width of the screen. Since almost all mobile devices have a maximum screen width of 480 pixels (currently), it is pretty reliable:

 if( screen.width <= 480 ) { location.href = '/mobile.html'; } 

The user agent string is also the place to view. However, the first solution is still better, because even if some erroneous device does not respond correctly for the user agent, the width of the screen does not lie.

The only exception here is a tablet PC such as an ipad. These devices have a larger screen width than smartphones, and I will probably go with the user-agent command for them.

+20
Jul 12 2018-11-17T00:
source share
 if(navigator.userAgent.match(/iPad/i)){ //code for iPad here } if(navigator.userAgent.match(/iPhone/i)){ //code for iPhone here } if(navigator.userAgent.match(/Android/i)){ //code for Android here } if(navigator.userAgent.match(/BlackBerry/i)){ //code for BlackBerry here } if(navigator.userAgent.match(/webOS/i)){ //code for webOS here } 
+13
Apr 08 '13 at 2:01
source share
 var isMobileDevice = navigator.userAgent.match(/iPad|iPhone|iPod/i) != null || screen.width <= 480; 
+8
Nov 19 '12 at 13:57
source share

A simple solution can only be css. You can set styles in the stylesheet, and then customize them at the bottom. Modern smartphones act as if they are only 480 pixels wide, but in reality they are much larger. Code for detecting a smaller screen in css

 @media handheld, only screen and (max-width: 560px), only screen and (max-device-width: 480px) { #hoofdcollumn {margin: 10px 5%; width:90%} } 

Hope this helps!

+6
Feb 06 '13 at 18:34
source share

Starting in 2015, if you came across this question, then you should probably use window.matchMedia (and, if it's still 2015, polyfill for older browsers):

 if (matchMedia('handheld').matches) { //... } else { //... } 
+5
Jul 22 '15 at 13:07 on
source share

I'm using mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)

+4
Mar 27 '14 at 23:02
source share

So, I did it. Thanks everyone!

 <head> <script type="text/javascript"> function DetectTheThing() { var uagent = navigator.userAgent.toLowerCase(); if (uagent.search("iphone") > -1 || uagent.search("ipad") > -1 || uagent.search("android") > -1 || uagent.search("blackberry") > -1 || uagent.search("webos") > -1) window.location.href ="otherindex.html"; } </script> </head> <body onload="DetectTheThing()"> VIEW NORMAL SITE </body> </html> 
+4
Jul 14. '15 at 0:59
source share

You can use the user-agent string to detect this.

 var useragent = navigator.userAgent.toLowerCase(); if( useragent.search("iphone") ) ; // iphone else if( useragent.search("ipod") ) ; // ipod else if( useragent.search("android") ) ; // android etc 

Here you can find a list of useragent strings http://www.useragentstring.com/pages/useragentstring.php

+3
Jul 12 '11 at 15:43
source share

I advise you to check out http://wurfl.io/

In short, if you are importing a tiny JS file:

 <script type='text/javascript' src="//wurfl.io/wurfl.js"></script> 

you will have a JSON object that looks like this:

 { "complete_device_name":"Google Nexus 7", "is_mobile":true, "form_factor":"Tablet" } 

(suppose you use Nexus 7, of course), and you can do things like:

 WURFL.complete_device_name 

This is what you are looking for.

Disclaimer: I work for a company offering this free service. Thank.

+3
Mar 11 '14 at 17:18
source share

This is an example of how to check if a webpage is loaded in a desktop or mobile application.

JS will be executed when the page loads, and you can do certain things on the desktop when the page loads, for example, hide the barcode scanner.

  <!DOCTYPE html> <html> <head> <script type="text/javascript"> /* * Hide Scan button if Page is loaded in Desktop Browser */ function hideScanButtonForDesktop() { if (!(/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent))) { // Hide scan button for Desktop document.getElementById('btnLinkModelScan').style.display = "none"; } } //toggle scanButton for Desktop on page load window.onload = hideScanButtonForDesktop; </script> </head> 
+2
Nov 08 '16 at 10:12
source share

Determine what the User Agent is for the devices you need to simulate, and then check the variable for it.

eg:

 // var userAgent = navigator.userAgent.toLowerCase(); // this would actually get the user agent var userAgent = "iphone"; /* Simulates User Agent for iPhone */ if (userAgent.indexOf('iphone') != -1) { // some code here } 
+1
Jul 12 '11 at 15:41
source share

This is my version, very similar to the top one, but I think this is good for reference.

 if (mob_url == "") { lt_url = desk_url; } else if ((useragent.indexOf("iPhone") != -1 || useragent.indexOf("Android") != -1 || useragent.indexOf("Blackberry") != -1 || useragent.indexOf("Mobile") != -1) && useragent.indexOf("iPad") == -1 && mob_url != "") { lt_url = mob_url; } else { lt_url = desk_url; } 
0
03 Sep '13 at 7:31
source share

From mozilla developer site: Device-specific user agent strings

I believe this will be a little more “accurate” when specifically filtered for mobile devices.

0
Mar 03 '14 at 5:36
source share

Finding a device based on a user agent is not a good solution, it’s better to discover features like a touch device (in the new jQuery, they remove $.browser and use $.support ).

To detect a mobile phone, you can check for touch events:

 function is_touch_device() { return 'ontouchstart' in window // works on most browsers || 'onmsgesturechange' in window; // works on ie10 } 

Taken from What is the best way to detect a touchscreen device using JavaScript?

0
May 6 '14 at 11:08
source share

Just use DeviceDetection

 deviceDetection.deviceType // phone | tablet according to device 
0
Jul 18 '14 at 16:23
source share

Another possibility is to use mobile-detect.js . Try demo .

Using a browser:

 <script src="mobile-detect.js"></script> <script> var md = new MobileDetect(window.navigator.userAgent); // ... see below </script> 

Node.js / Express:

 var MobileDetect = require('mobile-detect'), md = new MobileDetect(req.headers['user-agent']); // ... see below 

Example:

 var md = new MobileDetect( 'Mozilla/5.0 (Linux; U; Android 4.0.3; en-in; SonyEricssonMT11i' + ' Build/4.1.A.0.562) AppleWebKit/534.30 (KHTML, like Gecko)' + ' Version/4.0 Mobile Safari/534.30'); // more typically we would instantiate with 'window.navigator.userAgent' // as user-agent; this string literal is only for better understanding console.log( md.mobile() ); // 'Sony' console.log( md.phone() ); // 'Sony' console.log( md.tablet() ); // null console.log( md.userAgent() ); // 'Safari' console.log( md.os() ); // 'AndroidOS' console.log( md.is('iPhone') ); // false console.log( md.is('bot') ); // false console.log( md.version('Webkit') ); // 534.3 console.log( md.versionStr('Build') ); // '4.1.A.0.562' console.log( md.match('playstation|xbox') ); // false 
0
26 Oct '16 at 8:57
source share

As I (seemingly unsuccessfully) looked for a suitable solution for my hack, I want to add my hack here, though: I just check the device’s orientation support, which seems to be the most significant difference between mobile and desktop:

var is_handheld = 0; // just global if (window.DeviceOrientationEvent) {is_handheld = 1;}

At the same time, the imho page should also offer a manual choice between the layout of the mobile / desktop. I got 1920 * 1080, and I can zoom in - the simplified and reduced in function collocation is not always good. Especially forcing a layout based on the detection of a non-working device - this happens all the time.

0
Nov 23 '17 at 11:46 on
source share

Testing for a user agent is complex, dirty, and invariably fails. I also did not find that matching media for “portable” works for me. The easiest solution was to determine if the mouse was available. And it can be done like this:

 var result = window.matchMedia("(any-pointer:coarse)").matches; 

This will tell you if you need to show guidance elements or not, and everything else that requires a physical pointer. You can then determine the size for further media queries based on the width.

The next small library is a version of the request with brackets, which should cover most of the scenarios "You are a tablet or a phone without a mouse."

https://patrickhlauke.imtqy.com/touch/touchscreen-detection/

Media matches have been supported since 2015, and you can check compatibility here: https://caniuse.com/#search=matchMedia

In short, you must support variables regarding whether the screen is touch-sensitive and how large the screen is. In theory, I could have a tiny screen on a desktop controlled by a mouse.

0
Mar 15 '19 at 16:09
source share

Similar to a few answers above. This simple function works very well for me. This is relevant for 2019

 function IsMobileCard() { var 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|\-[aw])|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; } 
0
May 19 '19 at 10:56
source share



All Articles