简体   繁体   English

如何使用 JavaScript 检测移动设备?

[英]How to detect a mobile device with JavaScript?

I have been asked to create an actual HTML page / JavaScript to simulate detection of the mobile devices (iPhone / iPad / Android) using JavaScript code. I have been asked to create an actual HTML page / JavaScript to simulate detection of the mobile devices (iPhone / iPad / Android) using JavaScript code. This will then take the user to a different screen which asks them for their email address.然后,这会将用户带到另一个屏幕,询问他们的 email 地址。

I know this answer is coming 3 years late but none of the other answers are indeed 100% correct.我知道这个答案迟到了 3 年,但其他答案都不是 100% 正确的。 If you would like to detect if the user is on ANY form of mobile device (Android, iOS, BlackBerry, Windows Phone, Kindle, etc.), then you can use the following code:如果您想检测用户是否使用任何形式的移动设备(Android、iOS、BlackBerry、Windows Phone、Kindle 等),那么您可以使用以下代码:

if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent)) {
    // Take the user to a different screen here.
}

You would detect the requesting browsers user agent string, and then decide based on what it is if it's coming from a mobile browser or not.您将检测请求的浏览器用户代理字符串,然后根据它是否来自移动浏览器来决定它是什么。 This device is not perfect, and never will be due to the fact that user agents aren't standardized for mobile devices (at least not to my knowledge).这个设备并不完美,而且永远不会是因为用户代理没有针对移动设备进行标准化(至少据我所知不是这样)。

This site will help you create the code: http://www.hand-interactive.com/resources/detect-mobile-javascript.htm该站点将帮助您创建代码: http://www.hand-interactive.com/resources/detect-mobile-javascript.htm

Example :示例

You could get the user agent in javascript by doing this:您可以通过执行以下操作在 javascript 中获取用户代理:

var uagent = navigator.userAgent.toLowerCase();

And then do the check's in the same format as this (just using iPhone as a quick example, but others would need to be a little bit different)然后以与此相同的格式进行检查(仅以 iPhone 为例,但其他人需要稍有不同)

function DetectIphone()
{
   if (uagent.search("iphone") > -1)
      alert('true');
   else
      alert('false');
}

Edit编辑

You'd create a simple HTML page like so:您将创建一个简单的 HTML 页面,如下所示:

<html>
    <head>
        <title>Mobile Detection</title>
    </head>
    <body>
        <input type="button" OnClick="DetectIphone()" value="Am I an Iphone?" />
    </body>
</html>
<script>
    function DetectIphone()
    {
       var uagent = navigator.userAgent.toLowerCase();
       if (uagent.search("iphone") > -1)
          alert('true');
       else
          alert('false');
    }
</script>

A pretty simple solution is to check for the screen width.一个非常简单的解决方案是检查屏幕宽度。 Since almost all mobile devices have a max screen width of 480px (at present), it's pretty reliable:由于几乎所有移动设备的最大屏幕宽度为 480 像素(目前),因此非常可靠:

if( screen.width <= 480 ) {
    location.href = '/mobile.html';
}

The user-agent string is also a place to look.用户代理字符串也是一个可以查看的地方。 However, the former solution is still better since even if some freaking device does not respond correctly for the user-agent, the screen width doesn't lie.但是,前一种解决方案仍然更好,因为即使某些该死的设备没有正确响应用户代理,屏幕宽度也不会说谎。

The only exception here are tablet pc's like the ipad.这里唯一的例外是平板电脑,如 ipad。 Those devices have a higher screen width than smartphones and I would probably go with the user-agent-string for those.这些设备的屏幕宽度比智能手机高,我可能会使用 go 和用户代理字符串。

if(navigator.userAgent.match(/iPad/i)){
 //code for iPad here 
}

if(navigator.userAgent.match(/iPhone/i)){
 //code for iPhone here 
}


if(navigator.userAgent.match(/Android/i)){
 //code for Android here 
}



if(navigator.userAgent.match(/BlackBerry/i)){
 //code for BlackBerry here 
}


if(navigator.userAgent.match(/webOS/i)){
 //code for webOS here 
}
var isMobileDevice = navigator.userAgent.match(/iPad|iPhone|iPod/i) != null 
    || screen.width <= 480;

A simple solution could be css-only.一个简单的解决方案可能是纯 CSS 的。 You can set styles in your stylesheet, and then adjust them on the bottom of it.您可以在样式表中设置 styles,然后在其底部进行调整。 Modern smartphones act like they are just 480px wide, while they are actually a lot more.现代智能手机看起来只有 480 像素宽,但实际上要宽得多。 The code to detect a smaller screen in css is在 css 中检测较小屏幕的代码是

@media handheld, only screen and (max-width: 560px), only screen and (max-device-width: 480px)  {
    #hoofdcollumn {margin: 10px 5%; width:90%}
}

Hope this helps!希望这可以帮助!

I use mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)我使用mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)

So I did this.所以我做了这个。 Thank you all!谢谢你们!

<head>
<script type="text/javascript">
    function DetectTheThing()
    {
       var uagent = navigator.userAgent.toLowerCase();
       if (uagent.search("iphone") > -1 || uagent.search("ipad") > -1 
       || uagent.search("android") > -1 || uagent.search("blackberry") > -1
       || uagent.search("webos") > -1)
          window.location.href ="otherindex.html";
    }
</script>

</head>

<body onload="DetectTheThing()">
VIEW NORMAL SITE
</body>

</html>

Since it's now 2015, if you stumbled across this question then you should probably be using window.matchMedia (and, if it's still 2015, polyfilling for older browsers):由于现在是 2015 年,如果您偶然发现了这个问题,那么您可能应该使用window.matchMedia (并且,如果它仍然是 2015 年,则为旧浏览器填充):

if (matchMedia('handheld').matches) {
    //...
} else {
    //...
}

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 object 看起来像:

{
 "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)并且您将能够执行以下操作:

WURFL.complete_device_name

This is what you are looking for.这就是你要找的。

Disclaimer: I work for the company that offers this free service.免责声明:我为提供这项免费服务的公司工作。 Thanks.谢谢。

You can use the user-agent string to detect this.您可以使用用户代理字符串来检测这一点。

var useragent = navigator.userAgent.toLowerCase();

if( useragent.search("iphone") )
    ; // iphone
else if( useragent.search("ipod") )
    ; // ipod
else if( useragent.search("android") )
    ; // android
etc

You can find a list of useragent strings here http://www.useragentstring.com/pages/useragentstring.php您可以在此处找到用户代理字符串列表http://www.useragentstring.com/pages/useragentstring.php

This is an example of how to check if webpage is loaded in Desktop or mobile app.这是如何检查网页是否在桌面或移动应用程序中加载的示例。

JS will execute on page load and you can do Desktop specific things on page load eg hide barcode scanner. JS 将在页面加载时执行,您可以在页面加载时执行特定于桌面的操作,例如隐藏条形码扫描仪。

   <!DOCTYPE html>
    <html>
    <head>
     <script type="text/javascript">

            /*
            * Hide Scan button if Page is loaded in Desktop Browser
            */
            function hideScanButtonForDesktop() {

                if (!(/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent))) {

                    // Hide scan button for Desktop
                    document.getElementById('btnLinkModelScan').style.display = "none";
                }         
            }

            //toggle scanButton for Desktop on page load
            window.onload = hideScanButtonForDesktop;
        </script>
    </head>

Device detection based on user-agent is not very good solution, better is to detect features like touch device (in new jQuery they remove $.browser and use $.support instead).基于用户代理的设备检测不是很好的解决方案,更好的是检测触摸设备等功能(在新的 jQuery 中,他们删除$.browser并改用$.support )。

To detect mobile you can check for touch events:要检测移动设备,您可以检查触摸事件:

function is_touch_device() {
  return 'ontouchstart' in window // works on most browsers 
      || 'onmsgesturechange' in window; // works on ie10
}

Taken from What's the best way to detect a 'touch screen' device using JavaScript?取自使用 JavaScript 检测“触摸屏”设备的最佳方法是什么?

Determine what the User Agent is for the devices that you need to simulate and then test a variable against that.确定您需要模拟的设备的用户代理是什么,然后针对它测试一个变量。

for example:例如:

// var userAgent = navigator.userAgent.toLowerCase(); // this would actually get the user agent

var userAgent = "iphone"; /* Simulates User Agent for iPhone */
if (userAgent.indexOf('iphone') != -1) {
   // some code here
}

The cleanest way of finding device type is:查找设备类型的最简洁方法是:

if (navigator.userAgentData.mobile) { // do something }

(although it isn't yet supported on Safari) (虽然 Safari 尚不支持)

More info: https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData/mobile更多信息: https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData/mobile

This is my version, quite similar to the upper one, but I think good for reference.这是我的版本,和上面的很像,不过我觉得还是可以参考的。

if (mob_url == "") {
  lt_url = desk_url;
} else if ((useragent.indexOf("iPhone") != -1 || useragent.indexOf("Android") != -1 || useragent.indexOf("Blackberry") != -1 || useragent.indexOf("Mobile") != -1) && useragent.indexOf("iPad") == -1 && mob_url != "") {
  lt_url = mob_url;
} else {
  lt_url = desk_url;
}

Simply use DeviceDetection只需使用DeviceDetection

deviceDetection.deviceType // phone | tablet according to device

Another possibility is to use mobile-detect.js .另一种可能性是使用mobile-detect.js Try the demo .试试演示

Browser usage:浏览器使用:

<script src="mobile-detect.js"></script>
<script>
    var md = new MobileDetect(window.navigator.userAgent);
    // ... see below
</script>

Node.js / Express: Node.js / 快递:

var MobileDetect = require('mobile-detect'),
    md = new MobileDetect(req.headers['user-agent']);
// ... see below

Example:例子:

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

As I (kind of without success) searched for the proper solution for my hack, I want to add my hack here nonetheless: I simply check for support of device orientation, which seems the most significant diffrence between mobiles and desktop:当我(有点没有成功)为我的 hack 寻找合适的解决方案时,我仍然想在这里添加我的 hack:我只是检查设备方向的支持,这似乎是手机和桌面之间最显着的差异:

var is_handheld=0; var is_handheld=0; // just a global if(window.DeviceOrientationEvent) {is_handheld=1;} // 只是一个全局 if(window.DeviceOrientationEvent) {is_handheld=1;}

That being said, imho a page should also offer manual choice between mobile / desktop layout.话虽如此,恕我直言,页面还应该提供移动/桌面布局之间的手动选择。 I got 1920*1080 and I can zoom in - an oversimplified and feature-reduced wordpressoid chunk is not always a good thing.我得到了 1920*1080 并且可以放大 - 过度简化和功能减少的 wordpressoid 块并不总是一件好事。 Especially forcing a layout based on nonworking device detection - it happens all the time.特别是强制基于非工作设备检测的布局 - 它一直在发生。

Testing for user agent is complex, messy and invariably fails.对用户代理的测试是复杂的、混乱的并且总是失败的。 I also didn't find that the media match for "handheld" worked for me.我也没有发现“手持”的媒体匹配对我有用。 The simplest solution was to detect if the mouse was available.最简单的解决方案是检测鼠标是否可用。 And that can be done like this:这可以这样做:

var result = window.matchMedia("(any-pointer:coarse)").matches;

That will tell you if you need to show hover items or not and anything else that requires a physical pointer.这将告诉您是否需要显示 hover 项目以及其他任何需要物理指针的项目。 The sizing can then be done on further media queries based on width.然后可以根据宽度对进一步的媒体查询进行大小调整。

The following little library is a belt braces version of the query above, should cover most "are you a tablet or a phone with no mouse" scenarios.下面的小库是上面查询的一个大括号版本,应该涵盖大多数“你是平板电脑还是没有鼠标的手机”的场景。

https://patrickhlauke.github.io/touch/touchscreen-detection/https://patrickhlauke.github.io/touch/touchscreen-detection/

Media matches have been supported since 2015 and you can check the compatibility here: https://caniuse.com/#search=matchMedia自 2015 年以来一直支持媒体匹配,您可以在此处查看兼容性: https://caniuse.com/#search=matchMedia

In short you should maintain variables relating to whether the screen is touch screen and also what size the screen is.简而言之,您应该维护与屏幕是否为触摸屏以及屏幕尺寸有关的变量。 In theory I could have a tiny screen on a mouse operated desktop.理论上,我可以在鼠标操作的桌面上拥有一个小屏幕。

Similar to several of the answers above.类似于上面的几个答案。 This simple function, works very well for me.这个简单的 function 对我来说效果很好。 It is current as of 2019它是截至 2019 年的最新版本

function IsMobileCard()
{
var check =  false;

(function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true;})(navigator.userAgent||navigator.vendor||window.opera);

return check;   
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM