前端js判断来访者是否为手机uaredirect.js

最近想实现一个功能,判断来访者是否是移动设备访问,包括手机、平板电脑和其他移动设备。通过网上查找到一种通过前端js跳转的方式。此JS为百度site app的,我们直接拿过来用:

http://siteapp.baidu.com/static/webappservice/uaredirect.js

使用时,需要引用一个函数跳转:

<script type="text/javascript">uaredirect("http://m.abc.com");</script>

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}}}};

 2015-4-2补充详细使用方法:

功能实现:判断来访者是否为移动设备访问,若是则跳转到手机版网址m.aaa.com

具体步骤:一般在网站底部加入以下代码:

<script src="https://siteapp.baidu.com/static/webappservice/uaredirect.js" type="text/javascript"></script>
<script type="text/javascript">uaredirect("http://m.aaa.com");</script>

2015-4-2补充拓展:

百度的这个js文件可以进行拓展,现在是判断是否是手机访问,我们可以改成判断是否为电脑访问。

功能实现:判断来访者是否为电脑访问,若是则跳转到电脑版网址www.aaa.com

具体步骤:修改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}}}};

保存为js文件,正常引用函数即可。

2015-4-2补充更多分析

其实这个百度这个js的核心代码是:

if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i))) {
	location.replace(f)

依然也是判断浏览器的userAgent进行跳转的。只不过百度app由于要跟自己的业务整合,多了其他一些代码。简单来说,这个函数应该是:

function uaredirect(f) {
	if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i))) {
		location.replace(f)
	}
}

改成反方向判断,就是在navigator.userAgent.match前面加个!就可以了

 

点赞