简体   繁体   English

浏览器中最简单的方法来检测手机

[英]Easiest way in browser to detect mobile phones

I use a script generator -- http://detectmobilebrowsers.com/ -- to detect mobile phones in order to redirect the page to a subdomain that has a special template for phones. 我使用脚本生成器 - http://detectmobilebrowsers.com/ - 来检测手机,以便将页面重定向到具有手机特殊模板的子域。

I'm only interested in mobile phones only. 我只对手机感兴趣。 Ipad, Android tablets will not be redirected. Ipad,Android平板电脑不会被重定向。 All I need to know is if this script covers IPhone 4 and IPhone 5, because I don't have these models to test it. 我需要知道的是,这个脚本是否涵盖了IPhone 4和IPhone 5,因为我没有这些模型来测试它。 Anyway, I have tested on Safari using Developer menu - user agent - Safari ios 4.3.3 Iphone, and the page is redirected as needed. 无论如何,我已经使用开发人员菜单 - 用户代理 - Safari ios 4.3.3 Iphone在Safari上进行了测试,并根据需要重定向页面。 Is this enough for what I want or I should use the following script too: 这对我想要的还是足够的,或者我也应该使用以下脚本:

var iphone4 = (window.screen.height == (960 / 2)) ? true : false;
var iphone5 = (window.screen.height == (1136 / 2)) ? true : false;
if (iphone4 && iphone5) {
    parent.location.href='http://www.mobile.mysite.com';
}

Yes, the regex from http://detectmobilebrowsers.com/ will detect iPhone (and iPod Touch for that matter) all versions... ip(hone|od) is the regex portion that will match it. 是的,来自http://detectmobilebrowsers.com/的正则表达式将检测所有版本的iPhone(和iPod Touch)... ip(hone|od)是匹配它的正则表达式部分。

if you wanted a script just for iPhone/iPod you could trim the aforementioned script down to: 如果您想要一个仅适用于iPhone / iPod的脚本,您可以将上述脚本修改为:

 (function (a, b) { if (/ip(hone|od)/i.test(a)) window.location = b } )(navigator.userAgent || navigator.vendor || window.opera, 'http://www.mobile.mysite.com'); 

EDIT: 编辑:

or instead use this script to detect Mobile devices 或者使用此脚本来检测移动设备

(function (a, b) { if (/Mobi/.test(a)) window.location = b }
)(navigator.userAgent || navigator.vendor || window.opera, 'http://www.mobile.mysite.com');

based on the recommendation of Browser detection using the user agent | 基于使用用户代理进行浏览器检测的建议 MDN : MDN

we recommend looking for the string "Mobi" anywhere in the User Agent to detect a mobile device. 我们建议在用户代理中的任何位置查找字符串“Mobi”以检测移动设备。 If the device is large enough that it's not marked with "Mobi", you should serve your desktop site (which, as a best practice, should support touch input anyway, as more desktop machines are appearing with touchscreens). 如果设备足够大以至于没有标记为“Mobi”,那么您应该为桌面站点提供服务(最佳做法是,无论如何都应支持触摸输入,因为更多台式机出现在触摸屏上)。

这应该工作。

var bIsMobile = (navigator.userAgent.toLowerCase().indexOf("mobile") != -1 && navigator.userAgent.toLowerCase().indexOf("ipad") == -1);

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

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