百度手机终端自动跳转JS脚本使用方法与代码详解
百度为站长提供的判断手机终端并自动跳转的JS脚本,极大方便了Web开发。本文详细介绍该脚本的使用方法,包括引入外部JS文件、调用uaredirect函数以及核心逻辑代码。同时提供压缩版代码及多种在线JS格式化工具推荐,帮助开发者快速实现移动端适配。
百度手机终端自动跳转JS脚本使用方法与代码详解
百度为站长提供判断手机终端类型并自动跳转的js脚本,极大方便站长及web开发人员,使用方法极其简单。
基础引入与调用示例
代码如下:
<script src="http://siteapp.baidu.com/static/webappservice/uaredirect.js" type="text/javascript"></script>
<SCRIPT type=text/javascript>uaredirect("手机站","WEB站");</SCRIPT>其中最为核心的js脚本格式化代码如下所示:
核心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
}
}
}
};建议站长及web开发人员使用如下压缩后的js脚本
压缩版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格式化工具
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
ES6模块化中js文件怎么用import和export交互
2026-11-05 17:00:48
JS读取本地文件时报错或无响应的常见原因
2026-11-05 16:32:31
let、const与var的区别:JavaScript变量声明最佳实践
2026-11-05 14:16:38
JS中直接定义静态二维数组的字面量写法
2026-11-05 14:16:08
JS 怎么查找字符串中所有匹配项的位置
2026-11-05 14:15:53
