我正在寻找一个函数,返回一个布尔值,如果用户正在使用移动浏览器与否。
我知道我可以使用导航器。userAgent并使用regex编写该函数,但是用户代理对于不同的平台来说太复杂了。我怀疑匹配所有可能的设备是否容易,我认为这个问题已经解决了很多次,所以应该有某种完整的解决方案来完成这样的任务。
我正在看这个网站,但不幸的是,脚本是如此神秘,我不知道如何使用它为我的目的,这是创建一个返回true/false的函数。
我正在寻找一个函数,返回一个布尔值,如果用户正在使用移动浏览器与否。
我知道我可以使用导航器。userAgent并使用regex编写该函数,但是用户代理对于不同的平台来说太复杂了。我怀疑匹配所有可能的设备是否容易,我认为这个问题已经解决了很多次,所以应该有某种完整的解决方案来完成这样的任务。
我正在看这个网站,但不幸的是,脚本是如此神秘,我不知道如何使用它为我的目的,这是创建一个返回true/false的函数。
当前回答
这样你就可以知道用户在使用哪个设备。
if (/ipad|tablet/i.test(navigator.userAgent)) {
console.log("it's a Ipad"); // your code here
}
else if (/mobile/i.test(navigator.userAgent)) {
console.log("it's a Mobile");
} else {
console.log("it's a Desktop");
}
其他回答
这里有一个简单的解决方案,来自facebook的弹弓
const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
if (isMobile) {
/* your code here */
}
UserAgent不是100%可靠的。
window.navigator.maxTouchPoints > 1;
这就够了!它排除了浏览器开发控制台中的电话模拟器。这对我来说很重要。
为了增加额外的控制层,我使用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;
}
我建议你去http://wurfl.io/看看
简而言之,如果你导入一个很小的JS文件:
<script type='text/javascript' src="//wurfl.io/wurfl.js"></script>
你将得到一个JSON对象,看起来像:
{
"complete_device_name":"Google Nexus 7",
"is_mobile":true,
"form_factor":"Tablet"
}
(当然,这是假设你使用的是Nexus 7),你将能够做以下事情:
if(WURFL.form_factor == "Tablet"){
//dostuff();
}
这就是你要找的。
免责声明:我为提供这项免费服务的公司工作。谢谢。
我遇到过一些情况,上面的答案对我不起作用。所以我想到了这个。可能对某人有帮助。
if(/iPhone|iPad|iPod|Android|webOS|BlackBerry|Windows Phone/i.test(navigator.userAgent)
|| screen.availWidth < 480){
//code for mobile
}
这取决于您的用例。如果你专注于屏幕使用屏幕。availWidth,或者你可以使用document.body. clientwidth如果你想基于document进行渲染。