DIV CSS 佈局教程網

兩款 JavaScript 腳本:判斷手機瀏覽器並自動跳轉 WAP 站
編輯:關於JavaScript     

隨著移動設備普及,企業的網絡宣傳早已不能只停留在 PC 端。很多公司站點早期只做了 PC 版,手機雖然也能訪問,但排版、字號、交互都不友好,用戶體驗打了折扣。

於是很自然的想法是:既然已經有了配套的 WAP 手機站,那麼當用戶用手機訪問主域名時,就自動判斷並跳轉到手機版。下面分享目前自己在用的兩種 JS 腳本。

第一種:直接內聯的 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 = "https://www.laozuo.org";  // 換成自己的 WAP 站地址
        }
    }
} catch (err) {}
</script>

第二種:封裝成函數,外部引用

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,然後在需要生效的頁面引入並調用:

<script src="mobile.js" type="text/javascript"></script>
<script type="text/javascript">uaredirect("https://www.laozuo.org");</script>

兩個細節值得注意

腳本裡的 urlhash.match("fromapp") 是一個約定:如果 URL 帶有 #fromapp 標記,就不跳轉。這在「手機站提供返回 PC 站入口」時非常有用,可以避免無限循環跳轉。

另外,第二種寫法用 location.replace 而非 location.href,好處是不留下歷史記錄,用戶按返回鍵不會又跳回 PC 版;同時判斷 bdmark 元素是否存在,避免特定頁面被誤跳。

兩款腳本經測試均可正常判斷手機瀏覽器並跳轉 WAP 站,需要的朋友直接取用即可。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved