ave*_*ave 808 javascript browser-detection mobile-browser platform-detection
我正在寻找一个函数,如果用户有移动浏览器,则返回布尔值.
我知道我可以使用navigator.userAgent正则表达式来使用和编写该函数,但是用户代理对于不同的平台来说太多了.我怀疑匹配所有可能的设备会很容易,我认为这个问题已经解决了很多次,所以应该有一些完整的解决方案来完成这样的任务.
我正在看这个网站,但遗憾的是脚本是如此神秘,以至于我不知道如何将它用于我的目的,即创建一个返回true/false的函数.
Mic*_*ets 1211
这是一个使用疯狂长而全面的正则表达式的函数,它根据用户是否正在使用移动设备进行浏览来返回真值或假值.
window.mobilecheck = function() {
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;
};
Run Code Online (Sandbox Code Playgroud)
对于那些希望在此测试中包含平板电脑的人(尽管可以说,您不应该),您可以使用以下功能:
window.mobileAndTabletcheck = function() {
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|android|ipad|playbook|silk/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;
};
Run Code Online (Sandbox Code Playgroud)
您可以通过简单地运行设备列表并检查useragent是否与以下内容匹配来执行此操作:
function detectmob() {
if( navigator.userAgent.match(/Android/i)
|| navigator.userAgent.match(/webOS/i)
|| navigator.userAgent.match(/iPhone/i)
|| navigator.userAgent.match(/iPad/i)
|| navigator.userAgent.match(/iPod/i)
|| navigator.userAgent.match(/BlackBerry/i)
|| navigator.userAgent.match(/Windows Phone/i)
){
return true;
}
else {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,由于您认为此方法不可靠,您可以假设分辨率为800x600或更低的任何设备也是移动设备,甚至更多地缩小您的目标(尽管现在许多移动设备的分辨率远高于此)
即
function detectmob() {
if(window.innerWidth <= 800 && window.innerHeight <= 600) {
return true;
} else {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
参考:
yoa*_*nea 312
怎么样:
if (typeof window.orientation !== 'undefined') { ... }
Run Code Online (Sandbox Code Playgroud)
...因为智能手机通常支持此属性,而桌面浏览器则不支持.
编辑:正如@Gajus所指出的,此解决方案现已弃用,不应使用(https://developer.mozilla.org/en-US/docs/Web/API/Window/orientation)
Mud*_*Ali 108
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i) || navigator.userAgent.match(/WPDesktop/i);
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
Run Code Online (Sandbox Code Playgroud)
如何使用
if( isMobile.any() ) alert('Mobile');
Run Code Online (Sandbox Code Playgroud)
要检查用户是否在特定移动设备上:
if( isMobile.iOS() ) alert('iOS');
Run Code Online (Sandbox Code Playgroud)
参考:http://www.abeautifulsite.net/blog/2011/11/detecting-mobile-devices-with-javascript
github上的增强版:https://github.com/smali-kazmi/detect-mobile-browser
San*_*osh 56
这是facebook的弹弓来源的简单解决方案
var isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
if (isMobile) {
/* your code here */
}
Run Code Online (Sandbox Code Playgroud)
Tig*_*ger 25
来到这里寻找一种简单,干净的方式来检测"触摸屏设备",我将其归类为手机和平板电脑.在当前的答案中没有找到一个干净的选择,但确实解决了以下可能也有帮助的人.
var touchDevice = ('ontouchstart' in document.documentElement);
Run Code Online (Sandbox Code Playgroud)
编辑:要同时支持带触摸屏和手机的桌面,您可以使用以下内容:
var touchDevice = (navigator.maxTouchPoints || 'ontouchstart' in document.documentElement);
Run Code Online (Sandbox Code Playgroud)
Joh*_*ers 14
没有完美的解决方案来检测JS代码是否在移动浏览器上执行,但在大多数情况下,以下两个选项都可以使用.
!function(a){var b=/iPhone/i,c=/iPod/i,d=/iPad/i,e=/(?=.*\bAndroid\b)(?=.*\bMobile\b)/i,f=/Android/i,g=/(?=.*\bAndroid\b)(?=.*\bSD4930UR\b)/i,h=/(?=.*\bAndroid\b)(?=.*\b(?:KFOT|KFTT|KFJWI|KFJWA|KFSOWI|KFTHWI|KFTHWA|KFAPWI|KFAPWA|KFARWI|KFASWI|KFSAWI|KFSAWA)\b)/i,i=/IEMobile/i,j=/(?=.*\bWindows\b)(?=.*\bARM\b)/i,k=/BlackBerry/i,l=/BB10/i,m=/Opera Mini/i,n=/(CriOS|Chrome)(?=.*\bMobile\b)/i,o=/(?=.*\bFirefox\b)(?=.*\bMobile\b)/i,p=new RegExp("(?:Nexus 7|BNTV250|Kindle Fire|Silk|GT-P1000)","i"),q=function(a,b){return a.test(b)},r=function(a){var r=a||navigator.userAgent,s=r.split("[FBAN");return"undefined"!=typeof s[1]&&(r=s[0]),s=r.split("Twitter"),"undefined"!=typeof s[1]&&(r=s[0]),this.apple={phone:q(b,r),ipod:q(c,r),tablet:!q(b,r)&&q(d,r),device:q(b,r)||q(c,r)||q(d,r)},this.amazon={phone:q(g,r),tablet:!q(g,r)&&q(h,r),device:q(g,r)||q(h,r)},this.android={phone:q(g,r)||q(e,r),tablet:!q(g,r)&&!q(e,r)&&(q(h,r)||q(f,r)),device:q(g,r)||q(h,r)||q(e,r)||q(f,r)},this.windows={phone:q(i,r),tablet:q(j,r),device:q(i,r)||q(j,r)},this.other={blackberry:q(k,r),blackberry10:q(l,r),opera:q(m,r),firefox:q(o,r),chrome:q(n,r),device:q(k,r)||q(l,r)||q(m,r)||q(o,r)||q(n,r)},this.seven_inch=q(p,r),this.any=this.apple.device||this.android.device||this.windows.device||this.other.device||this.seven_inch,this.phone=this.apple.phone||this.android.phone||this.windows.phone,this.tablet=this.apple.tablet||this.android.tablet||this.windows.tablet,"undefined"==typeof window?this:void 0},s=function(){var a=new r;return a.Class=r,a};"undefined"!=typeof module&&module.exports&&"undefined"==typeof window?module.exports=r:"undefined"!=typeof module&&module.exports&&"undefined"!=typeof window?module.exports=s():"function"==typeof define&&define.amd?define("isMobile",[],a.isMobile=s()):a.isMobile=s()}(this);
alert(isMobile.any ? 'Mobile' : 'Not mobile');Run Code Online (Sandbox Code Playgroud)
这个特定的浏览器嗅探代码是名为isMobile的库.
测试是否window.orientation定义:
var isMobile = window.orientation > -1;
alert(isMobile ? 'Mobile' : 'Not mobile');Run Code Online (Sandbox Code Playgroud)
并非所有触摸屏设备都是移动设备,反之亦然.因此,如果您想要专门为触摸屏实现某些功能,则不应测试您的浏览器是否在移动设备上运行,而是测试设备是否具有触摸屏支持:
var hasTouchscreen = 'ontouchstart' in window;
alert(hasTouchscreen ? 'has touchscreen' : 'doesn\'t have touchscreen');Run Code Online (Sandbox Code Playgroud)
Ras*_*org 12
要添加额外的控制层,我使用HTML5存储来检测它是使用移动存储还是桌面存储.如果浏览器不支持存储,我有一系列移动浏览器名称,我将用户代理与阵列中的浏览器进行比较.
这很简单.这是功能:
// Used to detect whether the users browser is an mobile browser
function isMobile() {
///<summary>Detecting whether the browser is a mobile browser or desktop browser</summary>
///<returns>A boolean value indicating whether the browser is a mobile browser or not</returns>
if (sessionStorage.desktop) // desktop storage
return false;
else if (localStorage.mobile) // mobile storage
return true;
// alternative
var mobile = ['iphone','ipad','android','blackberry','nokia','opera mini','windows mobile','windows phone','iemobile'];
for (var i in mobile) if (navigator.userAgent.toLowerCase().indexOf(mobile[i].toLowerCase()) > 0) return true;
// nothing found.. assume desktop
return false;
}
Run Code Online (Sandbox Code Playgroud)
gsx*_*y73 10
如许多人所述,依靠用户代理数据的移动目标是有问题的。指望屏幕大小也可以这样说。我的方法是借鉴CSS技术来确定界面是否触摸的方法。使用纯JavaScript(所有现代浏览器均支持),媒体查询,您可以轻松确定设备何时可移动。
function isMobile() {
var match = window.matchMedia || window.msMatchMedia;
if(match) {
var mq = match("(pointer:coarse)");
return mq.matches;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
gdi*_*ble 10
const isMobile = localStorage.mobile || window.navigator.maxTouchPoints > 1;\nRun Code Online (Sandbox Code Playgroud)\n\n\n自 2022 年 2 月 7 日起可在 CHROME + SAFARI 中运行 :: 结合功能检测并尝试此线程和其他站点中的所有内容。适用
\nlocalStorage.mobile于 Chrome 移动版;后者适用于 Safari 移动版。打开或不打开开发工具和/或在移动模拟器上都不会触发桌面浏览器。在撰写本文时,它会触发真正的移动浏览器,但不会触发桌面浏览器。
我还在 Win10 上的 Lenovo X1 Yoga(键盘或平板模式)上进行了测试
\nlocalStorage.mobile无论如何undefinedwindow.navigator.maxTouchPointsis 1falsewindow.navigator.maxTouchPointsis 10true这是一个比匹配更有效的userAgent解决方案......
function _isMobile(){
// if we want a more complete list use this: http://detectmobilebrowsers.com/
// str.test() is more efficent than str.match()
// remember str.test is case sensitive
var isMobile = (/iphone|ipod|android|ie|blackberry|fennec/).test
(navigator.userAgent.toLowerCase());
return isMobile;
}
Run Code Online (Sandbox Code Playgroud)
这样的事怎么样?
if(
(screen.width <= 640) ||
(window.matchMedia &&
window.matchMedia('only screen and (max-width: 640px)').matches
)
){
// Do the mobile thing
}
Run Code Online (Sandbox Code Playgroud)
根据MDN关于使用用户代理进行浏览器检测的文章,建议尽可能避免使用这种方法,并建议其他途径,例如特征检测。
但是,如果必须使用用户代理来检测设备是否可移动,则他们建议:
总之,我们建议在用户代理中的任意位置查找字符串“ Mobi”以检测移动设备。
因此,这种单线就足够了:
const isMobileDevice = window.navigator.userAgent.toLowerCase().includes("mobi");
检测移动设备或平板设备的一种非常好的方法是查看浏览器是否可以创建触摸事件.
纯JavaScript代码:
function isMobile() {
try{ document.createEvent("TouchEvent"); return true; }
catch(e){ return false; }
}
if (isMobile()) {
# do whatever you wanna do!
}
Run Code Online (Sandbox Code Playgroud)
这对我很有用,但笔记本电脑设备可能存在问题,包括触摸屏显示器.
我不确定触摸屏笔记本电脑是否会被检测为移动设备,因为我还没有测试过它.
这是单班轮
function isMobile() {
return (typeof window.orientation !== "undefined") || (navigator.userAgent.indexOf('IEMobile') !== -1);
};
Run Code Online (Sandbox Code Playgroud)
元素获得焦点后,立即将其模糊。Bootstrap-datepicker是一个非常受欢迎且维护良好的组件,在GitHub中拥有近10,000个星,它使用以下方法:
if (window.navigator.maxTouchPoints || 'ontouchstart' in document) {
this.input.blur();
}
Run Code Online (Sandbox Code Playgroud)
https://github.com/uxsolutions/bootstrap-datepicker
感谢Tigger的协助。
这是我对这个问题的重新思考解决方案.仍然不完美.唯一真正的解决方案是,如果设备制造商开始认真对待"移动"和"平板电脑"用户代理字符串.
window.onload = userAgentDetect;
function userAgentDetect() {
if(window.navigator.userAgent.match(/Mobile/i)
|| window.navigator.userAgent.match(/iPhone/i)
|| window.navigator.userAgent.match(/iPod/i)
|| window.navigator.userAgent.match(/IEMobile/i)
|| window.navigator.userAgent.match(/Windows Phone/i)
|| window.navigator.userAgent.match(/Android/i)
|| window.navigator.userAgent.match(/BlackBerry/i)
|| window.navigator.userAgent.match(/webOS/i)) {
document.body.className += ' mobile';
alert('True - Mobile - ' + navigator.userAgent);
} else {
alert('False - Mobile - ' + navigator.userAgent);
}
if(window.navigator.userAgent.match(/Tablet/i)
|| window.navigator.userAgent.match(/iPad/i)
|| window.navigator.userAgent.match(/Nexus 7/i)
|| window.navigator.userAgent.match(/Nexus 10/i)
|| window.navigator.userAgent.match(/KFAPWI/i)) {
document.body.className -= ' mobile';
document.body.className += ' tablet';
alert('True - Tablet - ' + navigator.userAgent);
} else {
alert('False - Tablet - ' + navigator.userAgent);
}
}
Run Code Online (Sandbox Code Playgroud)
当Nexus 7平板电脑只有Android UA字符串时会发生什么?首先,移动成为现实,后来平板电脑也成为现实,但平板电脑将从机身标签中删除Mobile UA字符串.
CSS:
body.tablet { background-color: green; }
body.mobile { background-color: red; }
Run Code Online (Sandbox Code Playgroud)
alert为发展添加了线条.Chrome控制台可以模拟许多手持设备.在那里测试.
编辑:
只是不要使用它,而是使用特征检测.有很多设备和品牌,以品牌为目标永远不会是正确的解决方案.
取决于用例。所有移动设备都需要电池。如果您追求的是在不耗尽电池的情况下计算能力,请使用Battery Status API:
navigator.getBattery().then(battery => {
battery.charging ? 'charging' : 'not charging';
});
Run Code Online (Sandbox Code Playgroud)
如果您要查找的是展示用途matchMedia,它会返回一个布尔值:
if (window.matchMedia("(min-width: 400px)").matches) {
/* the viewport is at least 400 pixels wide */
} else {
/* the viewport is less than 400 pixels wide */
}
Run Code Online (Sandbox Code Playgroud)
或者将它们结合起来,在平板设备上获得更好的用户体验。
UserAgent 并非 100% 可靠。
window.navigator.maxTouchPoints > 1;
Run Code Online (Sandbox Code Playgroud)
这已经足够了!它不包括浏览器开发控制台中的手机模拟器。这对我来说很重要。
| 归档时间: |
|
| 查看次数: |
915899 次 |
| 最近记录: |