用JS判斷用戶使用的是手機端還是pc端訪問


  最近項目中用到一個應用,當訪問同一個網站地址的時候,例如:www.xxx.com的時候,如果當前客戶端是pc則跳轉到專注於pc的部分,如果當前客戶機是手機,則跳轉到專注於手機的部分,秉承一貫的習慣,baidu or google,但發覺網上的解決辦法都不盡如人意,很多都是通過js讀取本地文件系統進行判斷,但經過測試,不能成功,而且通過js讀取本地文件系統會造成安全性問題,但作為開放的互聯網,我們不可能為每一部電腦設置安全性,於是自己動手,豐衣足食,以下就是我的解決辦法: 
  依然是用js,不過只需要用到 navigator.platform,這是鑒於讀取這個屬性並不會造成安全性問題,而且,普遍的操作系統都屈指可數 
   ~~~navigator.platform判斷系統類型,從而判斷是手機還是pc
  簡單的跳轉代碼如下: 
    if(navigator.platform.indexOf('Win32')!=-1){ 
        //go to pc 
     }else{ 
        // go to 手機 
      } 
 

 

-------------------------------------------------------

另一種方法  ~~~用 navigator.userAgent 判斷是否現在的手機瀏覽器,似乎 navigator.platform 比較簡單靠譜一點

<script type="text/javascript">  
function browserRedirect() {
var sUserAgent = navigator.userAgent.toLowerCase();
var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
var bIsMidp = sUserAgent.match(/midp/i) == "midp";
var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
var bIsAndroid = sUserAgent.match(/android/i) == "android";
var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
if (!(bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) ){
window.location.href=B頁面;
}
}
browserRedirect(); </script>

-------------------------------------------------------


用戶是手機訪問還是電腦方法 ~~~還是用 navigator.userAgent去判斷是否為手機瀏覽器,不過這個比較清晰一點

 代碼如下 復制代碼 
var is_iPd = navigator.userAgent.match(/(iPad|iPod|iPhone)/i) != null;
var is_mobi = navigator.userAgent.toLowerCase().match(/(ipod|iphone|android|coolpad|mmp|smartphone|midp|wap|xoom|symbian|j2me|blackberry|win ce)/i) != null;
if(is_mobi && window.location.search.indexOf("mv=fp")<0){
window.location.href="#";
}
 

瀏覽器類型

 代碼如下 復制代碼 
if(navigator.userAgent.indexOf("MSIE")>0){
   //ie
   }else if(navigator.userAgent.indexOf("Firefox")>0){
   //firefox
   }else if(navigator.userAgent.indexOf("Chrome")>0){
   //chrome
   }else if(navigator.userAgent.indexOf("Safari")>0){
   //safari
   }else{
   //this part can be used as opera area
   }

 

<script type="text/javascript">  
 
    <!--  
 
    //平台、設備和操作系統   
 
    var system ={  
 
        win : false,  
 
        mac : false,  
 
        xll : false 
 
    };  
 
    //檢測平台   
 
    var p = navigator.platform;  
 
    alert(p);  
 
    system.win = p.indexOf("Win") == 0;  
 
    system.mac = p.indexOf("Mac") == 0;  
 
    system.x11 = (p == "X11") || (p.indexOf("Linux") == 0);  
 
    //跳轉語句   
 
    if(system.win||system.mac||system.xll){//轉向后台登陸頁面  
 
        window.location.href="login.jsp";  
 
    }else{  
 
        window.location.href="wapLogin.jsp";  
 
    }  
 
    -->  
 
</script>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM