代码改变世界

isMobile 一个简单的JS库,用来检测移动设备

2015-04-06 11:17  RTdo  阅读(2827)  评论(0编辑  收藏  举报

点这里

github地址:https://github.com/kaimallea/isMobile

 

Example Usage

I include the minified version of the script, inline, and at the top of the <head>. Cellular connections tend to suck, so it would be wasteful overhead to open another connection, just to download <1kb of JS:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="utf-8">
 5     <script>
 6         // Minified version of isMobile included in the HTML since it's <1kb
 7         (function(i){var e=/iPhone/i,n=/iPod/i,o=/iPad/i,t=/(?=.*\bAndroid\b)(?=.*\bMobile\b)/i,r=/Android/i,d=/BlackBerry/i,s=/Opera Mini/i,a=/IEMobile/i,b=/(?=.*\bFirefox\b)(?=.*\bMobile\b)/i,h=RegExp("(?:Nexus 7|BNTV250|Kindle Fire|Silk|GT-P1000)","i"),c=function(i,e){return i.test(e)},l=function(i){var l=i||navigator.userAgent;this.apple={phone:c(e,l),ipod:c(n,l),tablet:c(o,l),device:c(e,l)||c(n,l)||c(o,l)},this.android={phone:c(t,l),tablet:!c(t,l)&&c(r,l),device:c(t,l)||c(r,l)},this.other={blackberry:c(d,l),opera:c(s,l),windows:c(a,l),firefox:c(b,l),device:c(d,l)||c(s,l)||c(a,l)||c(b,l)},this.seven_inch=c(h,l),this.any=this.apple.device||this.android.device||this.other.device||this.seven_inch},v=i.isMobile=new l;v.Class=l})(window);
 8 
 9 
10         // My own arbitrary use of isMobile, as an example
11         (function () {
12             var MOBILE_SITE = '/mobile/index.html', // site to redirect to
13                 NO_REDIRECT = 'noredirect'; // cookie to prevent redirect
14 
15             // I only want to redirect iPhones, Android phones and a handful of 7" devices
16             if (isMobile.apple.phone || isMobile.android.phone || isMobile.seven_inch) {
17 
18                 // Only redirect if the user didn't previously choose
19                 // to explicitly view the full site. This is validated
20                 // by checking if a "noredirect" cookie exists
21                 if ( document.cookie.indexOf(NO_REDIRECT) === -1 ) {
22                     document.location = MOBILE_SITE;
23                 }
24             }
25         })();
26     </script>
27 </head>
28 <body>
29     <!-- imagine lots of html and content -->
30 </body>
31 </html>

 

  

node.js usage

Installation

npm install ismobilejs

Usage
1 var isMobile = require('ismobilejs');
2 console.log(isMobile(req.headers['user-agent']).any);