Mobile Detection

How to detect a mobile device with JavaScript?

I have been asked to create an actual HTML page / JavaScript to simulate detection of the mobile devices (iPhone / iPad / Android) using JavaScript code. This will then take the user to a different screen which asks them for their email address.

21 Answers 21

I know this answer is coming 3 years late but none of the other answers are indeed 100% correct. If you would like to detect if the user is on ANY form of mobile device (Android, iOS, BlackBerry, Windows Phone, Kindle, etc.), then 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. >

You would detect the requesting browsers user agent string, and then decide based on what it is if it’s coming from a mobile browser or not. This device is not perfect, and never will be due to the fact that user agents aren’t standardized for mobile devices (at least not to my knowledge).

You could get the user agent in javascript by doing this:

var uagent = navigator.userAgent.toLowerCase(); 

And then do the check’s in the same format as this (just using iPhone as a quick example, but others would need to be a little bit different)

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

You’d create a simple HTML page like so:

        

But I am wondering what would be start? Create a dummy webpage and embedd this coding in there. Is it html that we will use in, because as I mentioned in my code above, I have nothing to start with.

Читайте также:  Get header with javascript

Great. Thanks for that. How about redirecting it to a different page. Do you think something like this would help? if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/Android/i))) < if (document.cookie.indexOf("iphone_redirect=false") == -1) window.location = "m.espn.go.com/wireless/?iphone&i=COMR";

Don’t forget that user agents can be changed, spoofed and may not reflect the current browser. That being said if a client spoofs/changes their UserAgent and you they the wrong view displayed it’s their own fault. There are other ways other than pure user agent although the user agent is typically the root of all detection. There is a really good (although outdated) example here github.com/ahand/mobileesp?files=1

A pretty simple solution is to check for the screen width. Since almost all mobile devices have a max screen width of 480px (at present), it’s pretty reliable:

The user-agent string is also a place to look. However, the former solution is still better since even if some freaking device does not respond correctly for the user-agent, the screen width doesn’t lie.

The only exception here are tablet pc’s like the ipad. Those devices have a higher screen width than smartphones and I would probably go with the user-agent-string for those.

Right!! I only need to detect iPhone or Android. So this shouldn’t be a problem, but just to let you know I have absolutely nothing to start with. Shall I create a dummy Webpage and embedd this! Also how would the detection be checked? Would I need to transfer the script to a phone?

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 >

Even though this code won’t execute more than one block since it’s checking one thing over and over again, this code should make use of else-if blocks because of that reason. Also, what if the user agent variable changes somehow in between blocks? It’ll execute more than 1 block, here.

You are right ,and don’t forget that code was 4 years ago 🙂 and there is now better tools or ways to do the same job

var isMobileDevice = navigator.userAgent.match(/iPad|iPhone|iPod/i) != null || screen.width  

+1 for regex matching allowing users to easily check for multiple devices in one shot. However, I would add for clarity that because you denote /i at the end of the regex for insensitive match there really is no need to camel case the search params. The following would be equivalent (and also search for android devices): .match(/ipad|iphone|ipod|android/i)

A simple solution could be css-only. You can set styles in your stylesheet, and then adjust them on the bottom of it. Modern smartphones act like they are just 480px wide, while they are actually a lot more. The code to detect a smaller screen in css is

@media handheld, only screen and (max-width: 560px), only screen and (max-device-width: 480px) < #hoofdcollumn > 

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

So I did this. Thank you all!

    VIEW NORMAL SITE  

Since it's now 2015, if you stumbled across this question then you should probably be using window.matchMedia (and, if it's still 2015, polyfilling for older browsers):

if (matchMedia('handheld').matches) < //. >else < //. >

Note from MDN Note: CSS2.1 and Media Queries 3 defined several additional media types (tty, tv, projection, handheld, braille, embossed, aural), but they were deprecated in Media Queries 4 and shouldn't be used.

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 

In a nutshell, if you import a tiny JS file:

you will be left with a JSON object that looks like:

(that's assuming you are using a Nexus 7, of course) and you will be able to do things like:

WURFL.complete_device_name 

This is what you are looking for.

Disclaimer: I work for the company that offers this free service. Thanks.

"You can use these services free of charge, as long as your website is publicly available and does not require fees or paid subscription to access." -web.wurfl.io/#wurfl-js

This is an example of how to check if webpage is loaded in Desktop or mobile app.

JS will execute on page load and you can do Desktop specific things on page load eg hide barcode scanner.

       

Testing for user agent is complex, messy and invariably fails. I also didn't find that the media match for "handheld" worked for me. The simplest solution was to detect if the mouse was available. And that can be done like this:

let isMouseAvailable = window.matchMedia("(any-pointer:coarse)").matches; 

That will tell you if you need to show hover items or not and anything else that requires a physical pointer. The sizing can then be done on further media queries based on width.

The following little library is a belt braces version of the query above, should cover most "are you a tablet or a phone with no mouse" scenarios.

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

In short you should maintain variables relating to whether the screen is touch screen and also what size the screen is. In theory I could have a tiny screen on a mouse operated desktop.

Источник

How to detect a mobile device with JavaScript

To detect if the user is using a mobile device in JavaScript, we can use the userAgent property.

This property is part of the navigator object and sent by the browser in HTTP headers. It contains information about the name, version, and platform of the browser.

With the value of userAgent , we can use a regular expression to test if it contains some keywords or not and then decide the type of the device (mobile, tablet, or desktop). Optionally, you can also combine this test with the width of the current window.

Here is a function that returns the type of device, the user is currently on:

const deviceType = () =>  const ua = navigator.userAgent; if (/(tablet|ipad|playbook|silk)|(android(. *mobi))/i.test(ua))  return "tablet"; > else if (/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(ua))  return "mobile"; > return "desktop"; >; 

Note that the above solution is not always reliable. The value of the userAgent can be easily changed. For example, when we use bots to scrape a website, we can pass a completely different user agent value to hide our identity. It will make it difficult to detect the actual device type.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

How to Detect a Mobile Device with JavaScript?

red and white happy birthday card

With web apps being used on mobile devices more than ever, checking for a mobile device in a web app is something that we need to do often.

In this article, we’ll look at how to detect if a mobile device is being used to run a web app with JavaScript.

Use Agent Detection

One way to check for a mobile device is to check the user agent.

This isn’t the best way to check if a user is using a mobile device since user agent strings can be spoofed easily.

However, it’s still an easy way to check what device is being used by the user.

To get the user agent string, we can use the navigator.userAgent property.

For instance, we can write:

if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) < //. >

We check for all the relevant keywords that indicate the user is using a mobile device with our web app with the regex.

Check Screen Size

We can also check the size of the screen that the user is loading the web app in.

For instance, we can write:

const isMobile = window.matchMedia("only screen and (max-width: 760px)").matches; if (isMobile) < //. >

If max-width is 760px or less, then we know the user is loading the web app on a mobile device.

The pixels are scaled in a mobile device so that the screen width is less than 760px for mobile devices also.

Check for Touch Events

We can also check for touch events in our JavaScript code.

For instance, we can write:

const isMobile = ('ontouchstart' in document.documentElement && navigator.userAgent.match(/Mobi/)); 

If the ontouchstart event is available in the browser, then it’s probably a mobile device since most mobile devices have touch screens.

The navigator.platform Property

The navigator.platform property also has a user agent string.

It’s more reliable than the navigation.userAgent property.

For instance, we can use it by writing:

if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) || (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.platform))) < // . >

Conclusion

We can detect whether a user is using a web app on a mobile device with JavaScript.

One way to check is to check the user agent.

Another way to check is to check screen sizes.

And we can also check if touch events are available in the browser.

Источник

Оцените статью