Home  >  Article  >  Web Front-end  >  Implementation code for JavaScript to obtain the mobile device model (JS to obtain the mobile phone model and system)

Implementation code for JavaScript to obtain the mobile device model (JS to obtain the mobile phone model and system)

亚连
亚连Original
2018-05-31 10:33:436871browse

This article mainly introduces the implementation code of JavaScript to obtain the mobile device model. Friends who need it can refer to it

We usually identify the user's access device in the browser through the User Agent field. , but through it we can only obtain general information, such as whether you are using Mac or Windows, and whether you are using iPhone or iPad. If I want to know which generation of iPhone you are using, this method will not work. Some time ago, I happened to have this need to identify the specific model of the mobile client (mainly iOS devices), so I thought about the implementation of this problem.

First of all, like everyone else, I thought of UA, but it turns out that this road won’t work. Just when I was bored fiddling with the browser's API one by one, suddenly a certain piece of code in an article reminded me. This article talks about how to obtain graphics device information through js. Because HTML5 supports canvas, the model of the graphics device, such as the model of the graphics card, can be obtained through the API.

(function () {
  var canvas = document.createElement('canvas'),
    gl = canvas.getContext('experimental-webgl'),
    debugInfo = gl.getExtension('WEBGL_debug_renderer_info');

  console.log(gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL));
})();

Run this code to get the model of the graphics card. If you run it on an iOS device, you will get something like Apple A9 GPU. information. And we know that the GPU model of each generation of iOS devices is different. For example, the iPhone 6 is A8, and the iPhone 6s is A9. Seeing this, you should probably know my idea, which is to identify the model of the device by identifying the model of the GPU.

However, there is a small flaw. Some devices are of the same generation, that is, the GPU models are exactly the same, such as iPhone 6s, iPhone 6s Plus, and iPhone SE. They all use Apple A9 GPU, how to distinguish them? You will find that the biggest difference between them is not the resolution? Through JavaScript, we can easily obtain the screen resolution, so that by combining the two methods, we can obtain the accurate model of the device.

Here is a sample URL, you can access it with your mobile phone
https://joyqi.github.io/mobile-device-js/example.html

I put all my codes On GitHub
https://github.com/joyqi/mobile-device-js

This thinking gave me some inspiration for solving problems. When we think about solutions, we start from the side Maybe there will be new discoveries. For example, our code currently cannot identify the iPad Air and iPad mini of the same generation because they have the same GPU and resolution. However, there are many solutions to continue this idea. For example, you can study these two The number of microphones and speakers of the device, and this number can also be obtained through JS:P

Complete test code

<html>
  <head>
    <title>Mobile Device Example</title>
    <script src="./device.js"></script>
  </head>
  <head>
    <h1>GPU: <script>document.write(MobileDevice.getGlRenderer());</script></h1>
    <h1>Device Models: <script>document.write(MobileDevice.getModels().join(&#39; or &#39;));</script></h1>
  </head>
</html>

device. js

(function () {
  var canvas, gl, glRenderer, models,
    devices = {
      "Apple A7 GPU": {
        1136: ["iPhone 5", "iPhone 5s"],
        2048: ["iPad Air", "iPad Mini 2", "iPad Mini 3"]
      },

      "Apple A8 GPU": {
        1136: ["iPod touch (6th generation)"],
        1334: ["iPhone 6"],
        2001: ["iPhone 6 Plus"],
        2048: ["iPad Air 2", "iPad Mini 4"]
      },

      "Apple A9 GPU": {
        1136: ["iPhone SE"],
        1334: ["iPhone 6s"],
        2001: ["iPhone 6s Plus"],
        2224: ["iPad Pro (9.7-inch)"],
        2732: ["iPad Pro (12.9-inch)"]
      },

      "Apple A10 GPU": {
        1334: ["iPhone 7"],
        2001: ["iPhone 7 Plus"]
      }
    };

  function getCanvas() {
    if (canvas == null) {
      canvas = document.createElement(&#39;canvas&#39;);
    }

    return canvas;
  }

  function getGl() {
    if (gl == null) {
      gl = getCanvas().getContext(&#39;experimental-webgl&#39;);
    }

    return gl;
  }

  function getScreenWidth() {
    return Math.max(screen.width, screen.height) * (window.devicePixelRatio || 1);
  }

  function getGlRenderer() {
    if (glRenderer == null) {
      debugInfo = getGl().getExtension(&#39;WEBGL_debug_renderer_info&#39;);
      glRenderer = debugInfo == null ? &#39;unknown&#39; : getGl().getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);
    }

    return glRenderer;
  }

  function getModels() {
    if (models == null) {
      var device = devices[getGlRenderer()];

      if (device == undefined) {
        models = [&#39;unknown&#39;];
      } else {
        models = device[getScreenWidth()];

        if (models == undefined) {
          models = [&#39;unknown&#39;];
        }
      }
    }

    return models;
  }

  if (window.MobileDevice == undefined) {
    window.MobileDevice = {};
  }

  window.MobileDevice.getGlRenderer = getGlRenderer;
  window.MobileDevice.getModels = getModels;
})();

JS gets the phone model and system

If you want to get some basic parameters of the phone through js, just To use navigator.userAgent, we can get some basic information about the browser. If we want to see the content of navigator.userAgent on the page, we can use document.write(navigator.userAgent); to print it to the page, so that we can see the specific content more clearly.

1. The following is the userAgent content in some mobile phones that I printed:

1. iphone6 ​​plus
Mozilla/5.0 (iPhone; CPU iPhone OS e9ba17b97217ae2fd3f892935d053cd710_2_154bdf357c58b8a65c66d7c19c8e4d114 like Mac OS X) AppleWebKit/602.4.6 (KHTML, like Gecko) Mobile/14D27

iphone7 plus
Mozilla/5.0 (iPhone; CPU iPhone OS a80cef128d8e145f6c8ee3fc2423b6bb10_3_154bdf357c58b8a65c66d7c19c8e4d114 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Mobile/14E304

2、Meizu
Mozilla/5.0 (Linux; a80cef128d8e145f6c8ee3fc2423b6bbAndroid 5.154bdf357c58b8a65c66d7c19c8e4d114; 23b116612d380f011eb8a2f2f43b221dm1 metal54bdf357c58b8a65c66d7c19c8e4d114 Build/ LMY47I) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/40.0.2214.127 Mobile Safari/537.36

3、Samsung
Mozilla/5.0 (Linux; 0888031e5554b7d0d086f35893c6564aAndroid 6.0.154bdf357c58b8a65c66d7c19c8e4d114; 23b116612d380f011eb8a2f2f43b221dSM-A800054bdf357c58b8a65c66d7c19c8e4d114 Build/MMB29M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/55.0.2883.91 Mobile Safari/537.36

4、Xiaomi
Mozilla/5.0 (Linux; a80cef128d8e145f6c8ee3fc2423b6bbAndroid 6.0.1d6d448110e0324953b5d7bc1e2b276ce; 23b116612d380f011eb8a2f2f43b221dRedmi Note 4X54bdf357c58b8a65c66d7c19c8e4d114 Build/MMB29M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/55.0.2883.91 Mobile Safari/ 537.36

From the above we can see that the iPhone field contains the iPhone field, and the system version field is marked in red above. 2, 3, and 4 are the userAgent contents of several Android mobile phones. If you observe carefully, it is not difficult to find that Android 5.1 and so on are the system versions. The blue one is the phone model. As for other content, including browser version, etc., there will be no explanation here. If you want to know the specific meaning and source of this userAgent content, you can refer to the following address for a detailed explanation:

Why do all browsers’ userAgents come with Mozilla

2、在网上查了下有木有现成的js能直接实现此功能,找到了一个mobile-detect.js。基本可以实现我们需要的参数,下载地址:

https://github.com/hgoebl/mobile-detect.js/

文档地址:

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

使用方法:

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

使用过程中ios没有什么问题,想获取的都可以获取到,不过Android并不是都能获取到。所以又对Android的做了单独处理。发现Android手机型号后面都带了一段Build/...。所以就以此做了下单独处理,来获取Android手机型号。下面是具体代码:

<!DOCTYPE html> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
<meta name="viewport" 
  content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no"> 
<title>JS获取手机型号和系统</title> 
</head> 
<body> 
</body> 
<script src="js/lib/jquery-1.11.1.min.js"></script> 
<script src="js/lib/mobile-detect.min.js"></script> 
<script> 
  //判断数组中是否包含某字符串 
  Array.prototype.contains = function(needle) { 
    for (i in this) { 
      if (this[i].indexOf(needle) > 0) 
        return i; 
    } 
    return -1; 
  } 
 
  var device_type = navigator.userAgent;//获取userAgent信息 
  document.write(device_type);//打印到页面 
  var md = new MobileDetect(device_type);//初始化mobile-detect 
  var os = md.os();//获取系统 
  var model = ""; 
  if (os == "iOS") {//ios系统的处理 
    os = md.os() + md.version("iPhone"); 
    model = md.mobile(); 
  } else if (os == "AndroidOS") {//Android系统的处理 
    os = md.os() + md.version("Android"); 
    var sss = device_type.split(";"); 
    var i = sss.contains("Build/"); 
    if (i > -1) { 
      model = sss[i].substring(0, sss[i].indexOf("Build/")); 
    } 
  } 
  alert(os + "---" + model);//打印系统版本和手机型号 
</script> 
</html>

得到结果:

iphone iOS10.21---iPhone

android AndroidOS6.01---Redmi Note 4X

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

JavaScript实现区块链

iview table render集成switch开关的实例

解决Vue.js 2.0 有时双向绑定img src属性失败的问题

The above is the detailed content of Implementation code for JavaScript to obtain the mobile device model (JS to obtain the mobile phone model and system). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn