Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5: Detecting if you're on mobile or pc with javascript? [duplicate]

What javascript code can I use to detect if users are on a mobile or pc/mac browser in HTML5?

like image 227
gustavdebruyn Avatar asked Aug 28 '14 07:08

gustavdebruyn


People also ask

How can I tell if a device is mobile 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.

How does Website detect mobile?

It works by examining information contained in the HTTP headers, particularly User Agent strings sent by all web-enabled devices. The User Agent is looked up in a database that returns any requested information including device type.

How can I check my mobile device?

Go to the Settings or Options menu, scroll to the bottom of the list, and check 'About phone', 'About device' or similar. The device name and model number should be listed.


Video Answer


1 Answers

I was looking into this a few years back. In short, you can't do this with 100% reliability. There seem to be 2 approaches commonly used to provide a 'best-guess':

1. User Agent Detection This is where you check what the client is claiming to be. e.g.

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
    // is mobile..
}

It's not perfect, since I believe it is fairly easy for this property to be altered accidentally or otherwise. Plus it is highly unlikely that this list will still be accurate in 2 years' / 2 weeks' / 2 days' time!

2. Using Client Capabilities As you can imagine, a more pragmatic approach - allows you to cater to the known physical capability of the client. e.g.

if( screen.width <= 480 ) {     
    // is mobile.. 
}

However this is not ideal either, since higher and higher pixel densities in modern devices give you a misleading result: appearing that you have more 'room' than you actually do. Plus different browsers may expose their capabilities through different means.

If anyone has any better ideas to robustly discern between desktop and device, please comment! :)

like image 74
ne1410s Avatar answered Sep 28 '22 06:09

ne1410s