我正在寻找一个函数,返回一个布尔值,如果用户正在使用移动浏览器与否。

我知道我可以使用导航器。userAgent并使用regex编写该函数,但是用户代理对于不同的平台来说太复杂了。我怀疑匹配所有可能的设备是否容易,我认为这个问题已经解决了很多次,所以应该有某种完整的解决方案来完成这样的任务。

我正在看这个网站,但不幸的是,脚本是如此神秘,我不知道如何使用它为我的目的,这是创建一个返回true/false的函数。


当前回答

这就是我用的。我知道userAgent嗅探是不受欢迎的,但我的需求恰好是排除的之一!

<script>
var brow = navigator.userAgent;
    if (/mobi/i.test(brow)) {
        alert('Mobile Browser');
        // Do something for mobile
    } else {
        alert('Not on Mobile');
        // Do something for non mobile
    }
</script>

其他回答

我认为这才是真正的保护方案。

测试在Chrome和Firefox,移动和桌面。

var ___isMobileDevice;
const isMobileDeviceCheck = () => {
    const mobileOsRegExp = "(Android|webOS|iPhone|iPod)";
    if(screen.width < 500 || navigator.userAgent.match('/'+mobileOsRegExp+'/i')) {
        ___isMobileDevice = true;
    }
    if (___isMobileDevice) {
        if (typeof window.orientation === "undefined") {
            ___isMobileDevice = false; 
        }
    }
    if (typeof navigator.userAgentData != "undefined" && !navigator.userAgentData.mobile) {
        ___isMobileDevice = false; 
    }
    if ( typeof window.orientation !== "undefined" && ___isMobileDevice ) {
        if (window.navigator.maxTouchPoints > 1 && (navigator.userAgentData.mobile || localStorage.mobile || 'ontouchstart' in document)) {
            // mobile device found
            console.log('Is mobile device!'); 
        }
    }
}
window.onresize = () => {
    isMobileDeviceCheck();
}
isMobileDeviceCheck();

PS:作为浏览器扩展的Useragent切换器不能用这段代码欺骗你。

返回'ontouchstart'在window && window.screen. availwidth < 768

这个怎么样,它扩展了上面的答案,但也检查了屏幕大小

我遇到过一些情况,上面的答案对我不起作用。所以我想到了这个。可能对某人有帮助。

if(/iPhone|iPad|iPod|Android|webOS|BlackBerry|Windows Phone/i.test(navigator.userAgent)
 || screen.availWidth < 480){
//code for mobile
}

这取决于您的用例。如果你专注于屏幕使用屏幕。availWidth,或者你可以使用document.body. clientwidth如果你想基于document进行渲染。

我建议你去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();
}

这就是你要找的。

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

根据MDN关于使用用户代理进行浏览器检测的文章,建议尽可能避免这种方法,并建议使用其他方法,如特征检测。

然而,如果必须使用用户代理作为检测设备是否移动的手段,他们建议:

总而言之,我们建议在中的任何地方查找字符串“Mobi” 用户代理检测移动设备。

因此,这一行代码就足够了:

const isMobileDevice = window.navigator.userAgent.toLowerCase().includes("mobi");

(更新):

正如@ zenwolf在评论中建议的那样,使用正则表达式会更好:

const isMobileDevice = /Mobi/i.test(window.navigator.userAgent)