使用百度出品的 uaredirect.js 來判斷客戶端是否為手機


目前一般的網站都分成了PC版和手機版,當訪問的瀏覽器是來自PC版時,則讓其訪問PC版的網頁,當訪問的瀏覽器是來自手機時,則讓其跳轉到手機版的地址。百度的uaredirect.js 就是一個小小的工具,實現了該跳轉的功能。

使用方法如下,在網站的首頁的頭部引入下面的js和代碼:

 

<script src="http://siteapp.baidu.com/static/webappservice/uaredirect.js" type="text/javascript"></script>
<script type="text/javascript">uaredirect("http://www.xxx.cn/xx/wap/index.html");</script>

 這樣在網站的入口處,就將PC端和手機端的訪問分別引向不同的地址。

uaredirect.js應該代表的是:user agent redirect 的含義,級根據不同的 user agent 重定向到不同的網址。

uaredirect.js 的源碼也很簡單:

function uaredirect(f){
	try{
		if(document.getElementById("bdmark")!=null){
			return
		}
		
		var b=false;
		if(arguments[1]){
			var e=window.location.host;
			var a=window.location.href;
			if(isSubdomain(arguments[1],e)==1){
				f=f+"/#m/"+a;b=true
			}else{
				if(isSubdomain(arguments[1],e)==2){
					f=f+"/#m/"+a;b=true
				}else{
					f=a;b=false
				}
			}
		}else{
			b=true
		}
		
		if(b){
			var c=window.location.hash;
			if(!c.match("fromapp")){
				if((navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i))){
					location.replace(f)
				}
			}
		}
	}catch(d){
		
	}
}

function isSubdomain(c,d){
	this.getdomain=function(f){
		var e=f.indexOf("://");
		if(e>0){
			var h=f.substr(e+3)
		}else{
			var h=f
		}
		var g=/^www\./;
		if(g.test(h)){
			h=h.substr(4)
		}
		return h
	};
	
	if(c==d){
		return 1
	}else{
		var c=this.getdomain(c);
		var b=this.getdomain(d);
		if(c==b){
			return 1
		}else{
			c=c.replace(".","\\.");
			var a=new RegExp("\\."+c+"$");
			if(b.match(a)){
				return 2
			}else{
				return 0
			}
		}
	}
};

 主要起作用的代碼為:

var c=window.location.hash;
if(!c.match("fromapp")){
   if((navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i))){
      location.replace(f)
   }
}

 如果userAgent是 iPhone, 或者iPod, 或者Android, 或者ios 則使用我們傳入函數 uaredirect("http://www.xxx.cn/xx/wap/index.html"); 中的url地址來取代當前的url地址,實現了跳轉到不同的url地址。

其實騰訊的 www.qq.com 的首頁中包含了對不同客戶端的更加細化的區分,我們查看他的首頁源碼,發現其中包含了下面一段代碼:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta content="text/html; charset=gb2312" http-equiv="Content-Type">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>騰訊首頁</title>
<script type="text/javascript">
if(window.location.toString().indexOf('pref=padindex') != -1){

}else{ if(/AppleWebKit.*Mobile/i.test(navigator.userAgent)
|| (/MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alcatel|BIRD|DBTEL|Dopod|PHILIPS|HAIER|LENOVO|MOT-|Nokia|SonyEricsson|SIE-|Amoi|ZTE/.test(navigator.userAgent))){ if(window.location.href.indexOf("?mobile")<0){ try{ if(/Android|Windows Phone|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)){ window.location.href="http://xw.qq.com/index.htm"; }else if(/iPad/i.test(navigator.userAgent)){ window.location.href="http://www.qq.com/pad/" }else{ window.location.href="http://xw.qq.com/simple/s/index/" } }catch(e){} } } } </script>

 


免責聲明!

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



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