How to test for mobile webkit

我是研究僧i 提交于 2019-12-03 00:33:38

Okay, so I guess my question was poorly worded or something, but a little digging around and I've found an acceptable solution that works with my use-case.

// Webkit detection script
Modernizr.addTest('webkit', function(){
return RegExp(" AppleWebKit/").test(navigator.userAgent);
});

// Mobile Webkit
Modernizr.addTest('mobile', function(){
return RegExp(" Mobile/").test(navigator.userAgent);
});

These two tests will add both the 'webkit' and 'mobile' classes to your html tag (or 'no-webkit' and 'no-mobile' if false) but will also allow you to conditionally load your preferred javascript library, depending on the situation.

In my case either toggling between JQuery or Zepto.js:

Modernizr.load([
            // test mobile webkit (zepto or jquery?)
            {
                test: Modernizr.webkit && Modernizr.mobile,
                nope: ['//ajax.googleapis.com/ajax/libs/jquery/1/jquery.js'],
                yep: [baseURL + 'js/lib/zepto.min.js']
            }]);

So when I detect a visitor is using a mobile-webkit browser (which is probably like 100% of iOS or Android devices out there), I can save them a considerable amount of overhead, and load regular JQuery for everyone else, if necessary. Since the syntax is so similar, plugins and other scripts will likely still work regardless of which framework ends up being loaded.

gillesv's answer is almost spot-on. However, I found that the Regex does not detect Webkit browsers on Android 2.2 & 2.3 (Froyo & Gingerbread). The userAgent does contain both the phrases 'AppleWebkit' and 'Mobile' but not with a forward slash at the end.

Modifying the code as follows works for me:

// Webkit detection script
Modernizr.addTest('webkit', function(){
  return RegExp(" AppleWebKit").test(navigator.userAgent);
});

// Mobile Webkit
Modernizr.addTest('mobile', function(){
  return RegExp(" Mobile").test(navigator.userAgent);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!