Home Web Front-end JS Tutorial 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)

May 31, 2018 am 10:33 AM
javascript

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));
})();
Copy after login

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>
Copy after login

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;
})();
Copy after login

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 10_2_1 like Mac OS X) AppleWebKit/602.4.6 (KHTML, like Gecko) Mobile/14D27

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

2、Meizu
Mozilla/5.0 (Linux; Android 5.1; m1 metal 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; Android 6.0.1; SM-A8000 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; Android 6.0.1; Redmi Note 4X 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
Copy after login

使用过程中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>
Copy after login

得到结果:

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

See all articles