2013/10/16

使用JavaScript解析行動裝置

解析裝置是否為行動裝置或是桌上型電腦,可以透過JavaScript的navigator.userAgent去擷取當前裝置的資訊,並透過資訊去比對,本篇文章參考『DETECTING MOBILE DEVICES WITH JAVASCRIPT


<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf8">
  <script type="text/javascript">

  var isMobile = {
   Android: function() {
    return navigator.userAgent.match(/Android/i);
   },
   BlackBerry: function() {
    return navigator.userAgent.match(/BlackBerry/i);
   },
   iOS: function() {
    return navigator.userAgent.match(/iPhone|iPad|iPod/i);
   },
   Opera: function() {
    return navigator.userAgent.match(/Opera Mini/i);
   },
   Windows: function() {
    return navigator.userAgent.match(/IEMobile/i);
   },
   any: function() {
    return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
   }
  };
  
  function test () {
   alert(isMobile.any()+" "+navigator.userAgent);
  }
  </script>
 
 </head>
 <body onload="test();">
 </body>
</html>




再Mac上執行結果

Android裝置執行結果



參考資料:
http://www.abeautifulsite.net/blog/2011/11/detecting-mobile-devices-with-javascript/
http://tw.newtonstudio.com/?p=60
http://www.w3schools.com/jsref/prop_nav_useragent.asp