本文介绍利用JavaScript实现手机访问PC域名时自动跳转至WAP站点的两种方法。第一种为内嵌脚本直接判断User Agent并修改location;第二种为封装uaredirect函数后在页面中引用。测试表明两种方案在安卓和iPhone设备上均有效,适用于企业官网的移动端适配场景。
移动端WAP跳转方案概述
随着移动互联网的普及,企业宣传渠道已从PC端扩展至移动端。当用户通过手机访问企业顶级域名时,系统需识别设备类型并重定向至专用的WAP站点。下文将详细阐述两种基于JavaScript的手机浏览器类型识别与跳转实现方案。
第一种方案采用直接嵌入JavaScript脚本的方式实现。
直接嵌入JS脚本方案
<script type="text/javascript">
try {
var urlhash = window.location.hash;
if (!urlhash.match("fromapp"))
{
if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios|iPad)/i)))
{
window.location="http://www.laozuo.org(更换成自己的WAP网站)";
}
}
}
catch(err)
{
}</script>
第二种方案相对复杂,涉及引用外部JS文件。
引用外部JS文件方案
function uaredirect(murl){
try {
if(document.getElementById("bdmark") != null){
return;
}
var urlhash = window.location.hash;
if (!urlhash.match("fromapp")){
if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios|iPad)/i))) {
location.replace(murl);
}
}
} catch(err){}
}
将上述脚本保存至 mobile.js 文件,随后在需调用的页面中引用以下2个JS调用文件。
具体实现代码如下:
<script src="mobile.js" type="text/javascript"></script>
<script type="text/javascript">uaredirect("http://www.laozuo.org(更换成自己的WAP网站)");</script>经在安卓和iPhone设备测试,上述两种方法均可正常执行。
以上即为通过两种方式实现根据手机浏览器类型跳转WAP手机网站的完整内容。