使用navigator.userAgent.toLowerCase()判斷瀏覽器的類型


在跨平台、瀏覽器、移動設備兼容的時候,要根據設備、瀏覽器做特定調整,所以我們經常會用到navigator.userAgent.toLowerCase()來進行判斷。

先來解釋一下意思,navigator是HTML中的內置對象,包含瀏覽器的信息;userAgent是navigator的屬性方法,可以返回由客戶機發送服務器的頭部的值,作用其實就是就是返回當前用戶所使用的是什么瀏覽器,toLowerCase()是將轉換為小寫。

區分Android、iphone、ipad:

 

[javascript]
 
  1. var ua = navigator.userAgent.toLowerCase();  
  2. if (/android|adr/gi.test(ua)) {  
  3.     // 安卓  
  4.        
  5. }else if(/\(i[^;]+;( U;)? CPU.+Mac OS X/gi.test(ua)){  
  6.     //蘋果  
  7.        
  8. }else if(/iPad/gi.test(ua)){  
  9.     //ipad  
  10.   
  11. }  

 

有些軟件是內置的瀏覽器,比如新浪微博、騰訊QQ(非QQ瀏覽器)和微信

(微信在6.0.2版本的時候做了改動,微信的分享功能在新版本跟以前不一樣了)為了兼容版本,要做以下操作:

注:新浪微博為1,QQ客戶端為2,微信低於6.0.2版本為3,高於6.0.2版本為4,其他為0。

 

[javascript]
 
  1. var ua = navigator.userAgent.toLowerCase();    
  2. if(ua.match(/weibo/i) == "weibo"){    
  3.     console.log(1);  
  4. }else if(ua.indexOf('qq/')!= -1){    
  5.     console.log(2);  
  6. }else if(ua.match(/MicroMessenger/i)=="micromessenger"){    
  7. var v_weixin = ua.split('micromessenger')[1];    
  8.     v_weixin = v_weixin.substring(1,6);    
  9.     v_weixin = v_weixin.split(' ')[0];    
  10. if(v_weixin.split('.').length == 2){    
  11.     v_weixin = v_weixin + '.0';    
  12. }    
  13. if(v_weixin < '6.0.2'){    
  14.     console.log(3);  
  15. }else{    
  16.     console.log(4);    
  17. }    
  18. }else{    
  19.     console.log(0);   
  20. }    

 

區分各個瀏覽器:

 

[javascript]
 
  1. var ua=navigator.userAgent.toLowerCase();    
  2. if(/msie/i.test(ua) && !/opera/.test(ua)){    
  3.     alert("IE");    
  4.     return ;    
  5. }else if(/firefox/i.test(ua)){    
  6.     alert("Firefox");    
  7.     return ;    
  8. }else if(/chrome/i.test(ua) && /webkit/i.test(ua) && /mozilla/i.test(ua)){    
  9.     alert("Chrome");    
  10.     return ;    
  11. }else if(/opera/i.test(ua)){    
  12.     alert("Opera");    
  13.     return ;    
  14. }else if(/iPad/i){   
  15.     alert("ipad");   
  16.     return ;   
  17. }  
  18.  if(/webkit/i.test(ua) &&!(/chrome/i.test(ua) && /webkit/i.test(ua) && /mozilla/i.test(ua))){    
  19.     alert("Safari");    
  20.     return ;    
  21. }else{    
  22.     alert("unKnow");    
  23. }    

 

 

chrome中:navigator.userAgent的值:
 

 

其實navigator.userAgent 也有bug,

在IOS中,時間的顯示格式一般是 '2016/11/11 11:11:11' ,所以對於安卓的'2016-11-11 11:11:11',是不適用於IOS的。

因此,我們用下面的代碼去判斷安卓系統,

 

[javascript]
 
  1. <span style="font-size:18px;">var isAdr = new Date('2016-11-11 11:11:11').getTime() > 0;</span>  
!isAdr就是IOS~~~

 

版權聲明:本文為博主原創文章,未經博主允許不得轉載。


免責聲明!

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



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