digdeep

凡是过去,皆是序幕。Read the fucking manual and source code.

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

目前一般的网站都分成了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>

 

posted on 2015-01-28 16:07  digdeep  阅读(3391)  评论(0编辑  收藏  举报
不懂数据库和Web安全的架构师不是一个好的程序员。