首頁 > web前端 > js教程 > 判斷訪客終端類型集錦_javascript技巧

判斷訪客終端類型集錦_javascript技巧

WBOY
發布: 2016-05-16 15:56:22
原創
1390 人瀏覽過

當用戶使用手機等行動終端存取網站時,我們可以透過程式偵測用戶終端類型,如果是手機用戶,則引導用戶造訪適配手機螢幕的行動網站。本文將介紹分別使用PHP和JAVASCRIPT程式碼判斷使用者終端類型。

PHP版

我們使用PHP的$_SERVER['HTTP_USER_AGENT']來取得手機用戶瀏覽器的用戶代理,然後匹配已有的各種手機瀏覽器代理庫,如果含有匹配的關鍵字,則判斷為手機(移動終端)用戶。

 
function is_mobile() { 
  $user_agent = $_SERVER['HTTP_USER_AGENT']; 
  $mobile_agents = array("240x320","acer","acoon","acs-","abacho","ahong","airness","alcatel","amoi", 
  "android","anywhereyougo.com","applewebkit/525","applewebkit/532","asus","audio", 
  "au-mic","avantogo","becker","benq","bilbo","bird","blackberry","blazer","bleu", 
  "cdm-","compal","coolpad","danger","dbtel","dopod","elaine","eric","etouch","fly ", 
  "fly_","fly-","go.web","goodaccess","gradiente","grundig","haier","hedy","hitachi", 
  "htc","huawei","hutchison","inno","ipad","ipaq","iphone","ipod","jbrowser","kddi", 
  "kgt","kwc","lenovo","lg ","lg2","lg3","lg4","lg5","lg7","lg8","lg9","lg-","lge-","lge9","longcos","maemo", 
  "mercator","meridian","micromax","midp","mini","mitsu","mmm","mmp","mobi","mot-", 
  "moto","nec-","netfront","newgen","nexian","nf-browser","nintendo","nitro","nokia", 
  "nook","novarra","obigo","palm","panasonic","pantech","philips","phone","pg-", 
  "playstation","pocket","pt-","qc-","qtek","rover","sagem","sama","samu","sanyo", 
  "samsung","sch-","scooter","sec-","sendo","sgh-","sharp","siemens","sie-","softbank", 
  "sony","spice","sprint","spv","symbian","tablet","talkabout","tcl-","teleca","telit", 
  "tianyu","tim-","toshiba","tsm","up.browser","utec","utstar","verykool","virgin", 
  "vk-","voda","voxtel","vx","wap","wellco","wig browser","wii","windows ce", 
  "wireless","xda","xde","zte"); 
  $is_mobile = false; 
  foreach ($mobile_agents as $device) { 
    if (stristr($user_agent, $device)) { 
      $is_mobile = true; 
      break; 
    } 
  } 
  return $is_mobile; 
} 
登入後複製

上述程式碼中函數is_mobile()來判斷使用者終端類型,將收集到的當今各種手機的HTTP_USER_AGENT歸結到陣列$mobile_agents中,並進行配對。使用時只需呼叫函數is_mobile()。如以下程式碼表示,當配對使用者為手機造訪時,頁面跳到網站手機版m.jb51.net。

 
if (is_mobile()) { 
  header('Location:http://m.jb51.net'); 
} else { 
  echo '请使用手机访问.'; 
} 
登入後複製

Javascript版

您也可以直接在前端頁面上加入一段Javascript腳本來判斷使用者的終端類型。 Javascript也是透過獲取瀏覽器的user-agent信息,然後匹配已有的user-agent資訊庫。

 
if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios|iOS|iPad|Backerry| 
WebOS|Symbian|Windows Phone|Phone)/i))) { 
  location.replace("http://m.jb51.net") 
}else{ 
  document.write("请使用手机访问."); 
} 
登入後複製

以上程式碼還不是很完善,有興趣的朋友歡迎補充。

當然,我們也可以透過響應式佈局來匹配各種不同螢幕,這樣可以節約開發成本,但是當客戶對行動網站的功能需求,對於獨立的行動網站最好是採用在網站入口處判斷用戶訪問終端類型,一般是我們在主站首頁就做判斷,如果是手機訪客則跳到手機版頁面,否則按正常PC方式訪問頁面。

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板