Git Product home page Git Product logo

mobile-detect.js's Introduction

mobile-detect.js

A loose port of Mobile-Detect to JavaScript.

This script will detect the device by comparing patterns against a given User-Agent string. You can find out information about the device rendering your web page:

  • mobile or not
  • if mobile, whether phone or tablet
  • operating system
  • Mobile Grade (A, B, C) REMARK: this is completely outdated: all current devices will return an 'A', so it's useless nowadays
  • specific versions (e.g. WebKit)

Current master branch is using detection logic from [email protected]

Live Demo

Demo/check (sorry about the missing styling) can be found here.

Warning

TL;DR: you should not use this library in your HTML page and it's less reliable when used server-side (Node.js)

As mentioned later, "User-Agent" based detection is not a reliable solution in most cases, because:

  • The rules (regular expressions) are constantly out-dated and incomplete
  • You have to update the detection code continuously
  • There are other ways to detect how your web application should behave:
  • Maybe there are some libraries out there (which are probably not free) doing a more reliable job

If you still want to (or have to) use this library, you should always encapsulate it with your own code, because chances a very high that you have to tweak the behaviour a bit or are not satisfied with the result of mobile-detect.js. Don't spread usage of MobileDetect all over your own code! As you can see in the issues, there are some "bugs", feature-requests, pull-requests where people are not so happy how MobileDetect works. But I cannot change its behaviour from version to version, even if this was reasonable from new users' point of view. I hope you show understanding.

At least there is a way to monkey-patch the library (see "Extending" below).

Usage

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

General

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

More Info ...

There is some documentation generated by JSDoc:

https://hgoebl.github.io/mobile-detect.js/doc/MobileDetect.html

Side Effects

Script creates the global property MobileDetect.

Modernizr Extension

When using Modernizr, you can include mobile-detect-modernizr.js. It will add the CSS classes mobile, phone, tablet and mobilegradea if applicable.

You can easily extend it, e.g. android, iphone, etc.

Size (bytes)

  • development: 70168
  • minified: 39585
  • minified + gzipped: 16556 (cat mobile-detect.min.js | gzip -9f | wc -c)

Installation

Bower (which you should not use for new projects)

$ bower install hgoebl/mobile-detect.js --save

Node.js / npm

$ npm install mobile-detect --save

CDN - jsDelivr

<script src="https://cdn.jsdelivr.net/npm/[email protected]/mobile-detect.min.js"></script>

cdnjs - cdnjs.com

<script src="https://cdnjs.cloudflare.com/ajax/libs/mobile-detect/1.4.5/mobile-detect.min.js"></script>

Extending/Modifying Behaviour

Though it is not recommended to rely on internal methods or structures of MobileDetect, you can alter the behaviour by replacing particular internal methods with your own implementations. If you feel like this is the only possibility, then go ahead and have a look at the source code and examples in tests/spec/MobileDetectSpec.js (search for "Extensibility").

Alternatives / Infos

Often device detection is the first solution in your mind. Please consider looking for other solutions like media queries and feature detection (e.g. w/ Modernizr). Maybe there are better (simpler, smaller, faster) device detection libraries, so here you have a list (order has no meaning apart from first element):

Mobile-Usage Statistics

If you have to provide statistics about how many and which mobile devices are hitting your web-site, you can generate statistics (data and views) with hgoebl/mobile-usage. There are many hooks to customize statistical calculation to your needs.

License

MIT-License (see LICENSE file).

Contributing

Your contribution is welcome. If you want new devices to be supported, please contribute to Mobile-Detect instead.

To run generate-script it is necessary to have Mobile-Detect as a sibling directory to mobile-detect.js/. (I tried to use git subtree but had some problems on Mac OS X - probably my fault...)

  • fork or clone serbanghita/Mobile-Detect
  • fork hgoebl/mobile-detect.js
  • run npm install
  • create branch
  • make changes and run grunt (needs PHP >= 5.4 in your path)
  • run browser test (tests/SpecRunner.html)
  • commit, push to your branch
  • create pull request

Testing

Browser

Open tests/SpecRunner.html in different browsers.

Node.js

$ npm test
$ # or
$ grunt jasmine_node

Donations

If you want, you can donate to Mobile-Detect.

TODO

  • Extend RegEx patterns so that test passes
  • support ES6 modules

mobile-detect.js's People

Contributors

0mp avatar awea avatar denich avatar hgoebl avatar irazasyed avatar jorrit avatar lukasdrgon avatar mgroenhoff avatar msheakoski avatar unclechu avatar zeke avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mobile-detect.js's Issues

Motorola G 2nd generation detection

The Motorola G 2nd generation is detected as tablet, but it is a phone. Could you add it to the phones list?

User agent is:

Mozilla/5.0 (Linux; Android 5.0.2; XT1068 Build/LXB22.46-28.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.94 Mobile Safari/537.36

Thanks!

webpack build error

Not builded if connect through webpack require (). Need changed this code

((function (undefined) {
    if (typeof define === 'function' && define.amd) {
        return define;
    } else if (typeof module !== 'undefined' && module.exports) {
        return function (factory) { module.exports = factory(); };
    } else if (typeof window !== 'undefined') {
        return function (factory) { window.MobileDetect = factory(); };
    } else {
        // please file a bug if you get this error!
        throw new Error('unknown environment');
    }
})());

on this

((function (undefined) {

    if (typeof module !== 'undefined' && module.exports) {
        return function (factory) { module.exports = factory(); };
    }
    else if (typeof define === 'function' && define.amd) {
        return define;
    } else if (typeof window !== 'undefined') {
        return function (factory) { window.MobileDetect = factory(); };
    } else {
        // please file a bug if you get this error!
        throw new Error('unknown environment');
    }
})());

Does not work

With recent changes:

  • mobile() does not recognize tablets
  • phone() does not work with iPhone

"UnknownPhome" under Opera Mini

My "Samsung S2 (GT-I9100) is detected as "UnknownPhone" under "Opera Mini 7.6.40234" and "Opera Mini (New) 8.0.1807.91281". It seems that mobile-detect.js cannot identify the userAgent.

The fallback to the regex of detectmobilebrowsers.com seems to work, because it throws "UnknownPhone". Now I use the following working code:

var md = new MobileDetect(window.navigator.userAgent);
if (md.mobile() || md.mobile()=="UnknownPhone" || md.mobile()=="UnknownMobile" || md.mobile()=="UnknownTablet") {
    // If a mobile or an unknown device (mobile, tablet, mobile) with not more than 600px is detected, switch to mobile site version
    location.href = "https://m.xyz.com/";

Mobile Chrome on unknown tablet not detected as mobile

Problem

Hi,

today i've run into trouble detecting Praktica tablet (TP750 3GGSM) as unknown tablet - or generally speaking as a mobile device - in Google Chrome (v39.0.2171.93) on Android 4.0.4.

User agent string reported by Chrome:

Mozilla/5.0 (Linux; Android 4.0.4; TP750 3GGSM Build/IMM76I) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.93 Safari/537.36

After investigating for a while I've figured out that the problem is in detectMobileBrowsers.fullPattern regular expression. According to documentation at https://developer.chrome.com/multidevice/user-agent UA string on Android contains Mobile keyword only for phones and not for tablets.

Possible solution

Possible solution would be to modify regular expression from:

/(android|bb\d+|meego).+mobile|...

to

/(android|bb\d+|meego).+(mobile)?|...

if it does not any have side effects.

Gets wrong iOS version

Hi, great thanks to this nice module!

I found a problem in detecting iOS version today.

var md = new MobileDetect( window.navigator.userAgent );
console.log( window.navigator.userAgent );
console.log( md.version('iOS') );

This code gets these results.

Mozilla/5.0 (iPhone; CPU iPhone OS 10_1_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Version/10.0 Mobile/14B100 Safari/602.1
10.11

My iPhone is iOS 10.1.1 but, response is 10.11.
Would you like to fix this?

Asus MemoPad FHD 10 Tablet

Thanks for sharing this util project.
I have a problem, Asus MemoPad FHD 10 Tablet is not recognized neither mobile device or tablet or phone.
Could you tell me if I have to do something to make it works?

Thanks' in advance

R.

Lenovo TAB 2 support

My Lenovo TAB 2 is detected as desktop. My device name in User Agent is "Lenovo TAB 2 A10-70L"

Destructured usage

If attempting to use destructuring when creating constructor like this:

const { os, userAgent } = new MobileDetect(window.navigator.userAgent);

The following error is thrown:

screen shot 2017-01-10 at 12 56 23 pm

It seems to be due to this being undefined when checking for the cache. A small check for the existence of this should fix the problem, but then I think it will no longer use the cache.

Will attempt a PR sometime soon.

The MobileDetect for node js is not working on Samsung galaxy S3‏

var MobileDetect = require('mobile-detect');

var ua='Mozilla/5.0 (Linux; U; Android 4.1.2; en-us; SPH-L710 Build/JZO54K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30';
var md = new MobileDetect(ua);

console.log(md.mobile());

Result is: NULL

Both tablet() and phone() return positive values for unknown mobile

Precondition:
Have use agent considered as Mobile but not Tablet, for instance Acer nr11:
"Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0; Acer; Allegro)"

Actual:
Both tablet() and phone() methods return positive value ("UnknownMobile").

Expected:
I suppose that calling tablet() or phone() in this case should return falsy value (null). Because generally table/phone checking are implemented like so:

if (md.tablet()) {}
//or
if (md.phone()) {}

but not like

if (md.tablet() && md.tablet() !== "UnknownMobile") {}

Galaxy s6 support

user agent

'Mozilla/5.0 (Linux; Android 5.0.2; SM-G920F Build/LRX22G) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.85 Mobile Safari/537.36'

Some useragents from browserstack could not be recognized

Example Screenshot:
Screenshot

Some more user agents:
Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; rv:11.0) like Gecko
Mozilla/5.0 (MSIE 10.0; Windows NT 6.1; Trident/5.0)
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36

Android User Agent not recognized

Hello,

the following two user agent strings are both not detected by library (first one seems to be a web view from android)

  • Mozilla/5.0 (Linux; Android 5.1.1; E5823 Build/32.0.A.4.11) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36
  • Mozilla/5.0 (Android 5.1.1; Mobile; rv:41.0) Gecko/41.0 Firefox/41.0

Thank you

is('MobileBot') not working

Testing against this user agent:

SAMSUNG-SGH-E250/1.0 Profile/MIDP-2.0 Configuration/CLDC-1.1 UP.Browser/6.2.3.3.c.1.101 (GUI) MMP/2.0 (compatible; Googlebot-Mobile/2.1; +http://www.google.com/bot.html)

is('MobileBot') returns false, seems like the check for utils.bot should come after utils.MobileBot on lines 262 and 263, since the regex for 'Google-Mobile' won't get a chance to fire since the regex for 'GoogleBot' will return true first.

From this list of mobile bots https://developers.google.com/webmasters/mobile-sites/references/googlebot?hl=en, I believe this might fix the last 2.

The first one:
Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)
will probably still return true only for a 'Bot'.

Thanks,
Darren

Cannot call method 'substr' of undefined

Sometimes we get the following error:

TypeError: Cannot call method 'substr' of undefined
    at isMobileFallback (/var/www/ourproject/node_modules/mobile-detect/mobile-detect.js:338:62)
    at prepareDetectionCache (/var/www/ourproject/node_modules/mobile-detect/mobile-detect.js:362:13)
    at MobileDetect.mobile (/var/www/ourproject/node_modules/mobile-detect/mobile-detect.js:433:13)

os() function could be improved

The os() function is a bit broken... It simply cycles through the oss rules, and returns the key of the first matching rule. If it's going to do this, the rules should be carefully re-ordered. For example, this is the user agent for Windows Phone 8.1:

Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; Microsoft; Virtual) like iPhone OS 7_0_3 Mac OS X AppleWebKit/537 (KHTML, like Gecko) Mobile Safari/537

It contains the string "Android" so it matches the first "Android" rule. Here's some explanation from Microsoft: http://blogs.msdn.com/b/ie/archive/2014/07/31/the-mobile-web-should-just-work-for-everyone.aspx

Even if it didn't contain "Android", it would match the "Windows Phone [0-9.]+" part of WindowsMobileOS. This isn't ideal - I assume we should be returning WindowsPhoneOS.

I wasn't sure whether to post this here or in the Mobile_Detect library... The os() function doesn't exist in the PHP library, and perhaps this is the reason...

Desktop support?

Why when using with desktop, these functions give blank result:

userAgent()
os()

And is this possible to do something like md.is('Desktop')?

Support for LG G Pad 8.3 (google play edition)

Currently comes back as desktop. UA is

Mozilla/5.0 (Linux; Android 4.4.2; LG-V510 Build/KOT49H.L004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.141 Safari/537.36

Suggested mod:

    "LGTablet": "\\bL-06C|LG-V\\d+|LG-VK\\d+\\b",

Works with browserify?

For the moment, I don't succeed to make it work with browserify.

var MobileDetect = require('mobile-detect')
var md           = new MobileDetect( window.navigator.userAgent )

console.log( md.mobile() ) // null
console.log( md.phone() ) // null
console.log( md.tablet() ) // null
console.log( md.userAgent() ) // null
console.log( md.os() ) // null
console.log( md.is('iPhone') ) // false
console.log( md.is('bot') ) // false
console.log( md.version('Webkit') ) // NaN
console.log( md.versionStr('Build') ) // null
console.log( md.match('playstation|xbox') ) // false
console.log( md ) // Object { ua: "Mozilla/5.0 (Macintosh; Intel Mac O…", _cache: Object, maxPhoneWidth: 600 }

Incorrect Typescript typings

In order to import the constructor in Typescript with the new typings you need have the following:

import {MobileDetect} from "mobile-detect";

But the source suggests that you need to import it using:

import * as MobileDetect from "mobile-detect";

or

import MobileDetect = require("mobile-detect");

Windows Phone detection

Hi!, great script, but it doesn't work OK with Windows Phone.. I've uploaded an screencapture taken with my Windows Phone - Lumia 1020 running IE 11, OS version 8.1

As you can see, it says os is Android, mobile() returns iPhone, and also is('iPhone') and is('AndroidOS') returns true

It would be wonderful if you can fix this problem and let me now then

Thanks in advance for all your effort

wp_ss_20141030_0001

Not working with Samsung Galaxy Tab 4

The UA is:
Mozilla/5.0 (Linux; Android 4.4.2; en-us; SAMSUNG SM-T530NU Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Version/1.5 Chrome/28.0.1500.94 Safari/537.36

Since the check for a phone is before that for a tablet, its being identified as a phone - mobielDetectRules for a phone contain the regex /Samsung/i. This causes the regex for a Samsung tablet /SAMSUNG.*Tablet/ to never be matched since the check for a phone is made before that for a tablet. Should the checking order be reversed (tablet, then phone)?

Support AMD?

Support AMD for using it with RequireJS?

UPD: See for pull request: #8

Galaxy s7 support

This is the current user agent -

'Mozilla/5.0 (Linux; Android 6.0.1; SM-G930F Build/MMB29K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.85 Mobile Safari/537.36'

Phablet category

This is not an issue but a feature proposal - it would be much appreciated to get extra category for phablets, which are currently detected as phones.

Different results of js and php libs

Example (Xiaomi Redmi Note 3 PRO, Android 5.1.1): Mozilla/5.0 (Linux; Android 5.1.1; Redmi Note 3 Build/LMY47V) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Mobile Safari/537.36

php:

js:
2017-03-07_03-27-12


Example (Asus ZenFone Max, Android 6.0.1): Mozilla/5.0 (Linux; Android 6.0.1; ASUS_Z010D Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Mobile Safari/537.36

php:

js:
2017-03-07_03-32-38

And maybe lots of others. I think, this is critical, these phones are not new. The latest version of library is used.

Related: #54

Galaxy Note 4 support

ua

'Mozilla/5.0 (Linux; Android 4.4.4; SM-N910C Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.85 Mobile Safari/537.36'

Why build so strange?

How I can build mobile-detect without php and this files?:
path.join(__dirname, '..', '..', 'Mobile-Detect', 'tests', 'ualist.json')

Why you don't using just grunt (or gulp), without generate script?

Unknown Environment - Google Big Query

I tried using this library as part of a UDF script in Google BigQuery and got the "Error: unknown environment" log message at like 990 (mobile-detect.js) and saw that the comment on the line above said that I should file a bug report when I got that error.

How can I help fix this issue?

Mobile type determining by screen width works incorrectly

I found an issue regarding to determining device based on screen width.
We divide screen width on device pixel ratio.

var physicalPixelWidth = window.screen.width,
  pixelRatio = window.devicePixelRatio || 1,
  cssPixelWidth = physicalPixelWidth / pixelRatio;

It's mistakenly because window.screen.width already has density independent pixels value (tested on several real devices).

So I suggest to eliminate this division.

Actually it'll be good to use smallest-width qualifier approach instead - the same as android use to determine small/large screen devices.

Failing to detect some mobile devices

In version 0.4.3, this user-agent:

Mozilla/5.0 (Linux; Android 5.0.2; SM-G9250 Build/LRX22G; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/43.0.2357.121 Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/35.0.0.48.273;]

Will give 'UnknownMobile' with the .phone() method call.

In version 1.2.0 the same method returns null.

Add to the phone list: Huawei, Meizu, Xiaomi

Hi! Thanks for this great lib. Is it possible to add to the phone list Huawei, Meizu and Xiaomi? These brands become more and more popular. FYI, during my tests on Huawei Honor 3C H30-U10 I had been receiving next values from methods:

  1. mobile() returns 'UnknownMobile'
  2. phone() returns null

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.