使用javascript检测手机/平板电脑/网络客户端

Mat*_*ang 7 javascript browser-detection device-detection

我试图检测最终用户是在手机,平板电脑还是个人电脑上

我已经谷歌搜索了一段时间,显然没有简单的解决方案.

好吧,我想我不应该使用Resolution,因为现在有些平板电脑具有惊人的分辨率.

我不应该依赖方向,因为windows8笔记本电脑可以像平板电脑一样旋转.(响应式设计对我目前的项目来说太难了)

我一直在尝试使用UserAgent(认为它也有它的缺点),但是无法让它工作,下面是我用来区分手机/平板电脑和PC的不同版本的联合,他们只是不工作和我不知道为什么

var agents = ['android', 'webos', 'iphone', 'ipad', 'blackberry','iemobile','phone','mobile'];
                for(i in agents) {
                    if(navigator.userAgent.toLowerCase().match('/'+agents[i]+'/i')) {
                        return true;
                    }
                }


if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
                return true;
            }

 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)
                 || navigator.userAgent.match(/bada/i)
                 || navigator.userAgent.match(/Bada/i)
                 ){
                return true;
            }
Run Code Online (Sandbox Code Playgroud)

Jan*_*nen 12

是的,您不应该依赖于解决方案或方向.但基于em的媒体查询呢?

要使用javascript读取媒体查询的结果,您可以尝试向css添加媒体查询,以向页面添加不可见内容:

@media all and (max-width: 45em) {
    body:after {
        content: 'smallscreen';
        display: none;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后通过javascript阅读内容:

var size = window.getComputedStyle(document.body,':after').getPropertyValue('content');
Run Code Online (Sandbox Code Playgroud)

然后确定要加载的内容:

if (size.indexOf('smallscreen') !=-1) {
    // Load some content for smaller screens.
}
Run Code Online (Sandbox Code Playgroud)