百度判断手机终端并自动跳转js代码及使用实例
百度目前为站长提供了判断手机终端类型并自动实现跳转的js脚本,极大的方便了广大站长及web开发人员。其js脚本的使用方法极其简单。
<scriptsrc="http://siteapp.baidu.com/static/webappservice/uaredirect.js"type="text/javascript"></script>
<SCRIPTtype=text/javascript>uaredirect("手机站","WEB站");</SCRIPT>
其中最为核心的js脚本格式化代码如下所示:
functionuaredirect(f){
try{
if(document.getElementById("bdmark")!=null){
return
}
varb=false;
if(arguments[1]){
vare=window.location.host;
vara=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){
varc=window.location.hash;
if(!c.match("fromapp")){
if((navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i))){
location.replace(f)
}
}
}
}catch(d){}
}
functionisSubdomain(c,d){
this.getdomain=function(f){
vare=f.indexOf("://");
if(e>0){
varh=f.substr(e+3)
}else{
varh=f
}
varg=/^www\./;
if(g.test(h)){
h=h.substr(4)
}
returnh
};
if(c==d){
return1
}else{
varc=this.getdomain(c);
varb=this.getdomain(d);
if(c==b){
return1
}else{
c=c.replace(".","\\.");
vara=newRegExp("\\."+c+"$");
if(b.match(a)){
return2
}else{
return0
}
}
}
};
建议站长及web开发人员使用如下压缩后的js脚本
functionuaredirect(f){try{if(document.getElementById("bdmark")!=null){return}varb=false;if(arguments[1]){vare=window.location.host;vara=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){varc=window.location.hash;if(!c.match("fromapp")){if((navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i))){location.replace(f)}}}}catch(d){}}functionisSubdomain(c,d){this.getdomain=function(f){vare=f.indexOf("://");if(e>0){varh=f.substr(e+3)}else{varh=f}varg=/^www\./;if(g.test(h)){h=h.substr(4)}returnh};if(c==d){return1}else{varc=this.getdomain(c);varb=this.getdomain(d);if(c==b){return1}else{c=c.replace(".","\\.");vara=newRegExp("\\."+c+"$");if(b.match(a)){return2}else{return0}}}};
PS:在此小编为大家推荐几款javascript格式化美化与压缩工具,类似上述的百度跳转代码压缩与格式化就可使用下述工具实现:
C语言风格/HTML/CSS/json代码格式化美化工具:
http://tools.jb51.net/code/ccode_html_css_json
在线JavaScript代码美化、格式化工具:
http://tools.jb51.net/code/js
JavaScript代码美化/压缩/格式化/加密工具:
http://tools.jb51.net/code/jscompress
JavaScript在线压缩工具:
http://tools.jb51.net/code/js_yasuo
JavaScript在线格式化工具(基于beautify.js插件):
http://tools.jb51.net/code/js_beautify