javascript 如何使用javascript检测平板电脑、手机、台式机、电视

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16520186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:59:37  来源:igfitidea点击:

How to detect tablet, mobile, desktop, tv using javascript

javascriptmobiletablet

提问by MAK Ripon

I am developing an web application where I need to detect the device from javascript. Could anybody tell me whats the best way to do it ? I found several solution by googling. But no one is full proof. I do not want to use server side detection like WURFL.

我正在开发一个 Web 应用程序,我需要在其中从 javascript 检测设备。谁能告诉我最好的方法是什么?我通过谷歌搜索找到了几个解决方案。但没有人能完全证明。我不想使用像 WURFL 这样的服务器端检测。

My update

我的更新

I am detecing device by matching CSS media queries using javascript. For media query matching using polyfill by Paul Irish https://github.com/paulirish/matchMedia.js/

我正在通过使用 javascript 匹配 CSS 媒体查询来检测设备。对于使用 Paul Irish https://github.com/paulirish/matchMedia.js/ 的polyfill 进行媒体查询匹配

回答by

You can use:

您可以使用:

1) JS: Detect by user agent

1)JS:由用户代理检测

if (navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i))

Take the user agent strings from here: http://www.useragentstring.com/pages/useragentstring.php.

从这里获取用户代理字符串:http: //www.useragentstring.com/pages/useragentstring.php

2) CSS: Use responsive design

2)CSS:使用响应式设计

3) JS: Detect the screen width by screen.width

3)JS:检测屏幕宽度 screen.width

回答by Luca Passani

I advise you check out http://wurfl.io/

我建议您查看http://wurfl.io/

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

简而言之,如果你导入一个很小的 ​​JS 文件:

<script type='text/javascript' src="//wurfl.io/wurfl.js"></script>

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

您将得到一个 JSON 对象,如下所示:

{
 "complete_device_name":"Google Nexus 7",
 "is_mobile":true,
 "form_factor":"Tablet"
}

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

(当然,这是假设您使用的是 Nexus 7)并且您将能够执行以下操作:

if(WURFL.form_factor == "Tablet"){
    //dostuff();
}

This is what you are looking for.

这就是你要找的。

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

免责声明:我为提供此免费服务的公司工作。谢谢。