本文提供兩個判斷訪客是否使用行動裝置的範例,常用於手機版網址跳轉,供需要的朋友參考。
<script>
function browserRedirect() {
var sUserAgent = navigator.userAgent.toLowerCase();
var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
var bIsMidp = sUserAgent.match(/midp/i) == "midp";
var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
var bIsAndroid = sUserAgent.match(/android/i) == "android";
var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
if (!(bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) ){
window.location.href='https://www.jb51.net';
}else{
//window.location.href='https://m.jb51.net';
}
}
$(function(){ browserRedirect(); });
</script>
這個寫法把已知的行動裝置關鍵字都列出來,只要命中任一項就視為行動裝置。缺點很明顯:清單維護成本高,新裝置一出現就漏判;而且把 PC 網址寫死成預設分支,邏輯是反過來的。
<script type="text/javascript">
(function(){
var reWriteUrl = function(url){
if(url){
var Splits = url.split("/"), siteName = window.location.pathname;
if(typeof siteName !== "undefined"){
return "https://m.jb51.net" + siteName;
}
}
};
if(/Android|webOS|iPhone|iPad|Windows Phone|iPod|BlackBerry|SymbianOS|Nokia|Mobile/i.test(navigator.userAgent)){
var url = window.location.href;
if(url.indexOf("?mobile") < 0){
try{
window.location.href = reWriteUrl(url);
}catch(e){}
}
}
})();
</script>
這個版本用單一正則一次比對,並保留原頁面的 pathname 拼到行動版網域上,比範例一乾淨。但仍有幾個問題:查詢字串與 hash 被丟掉了;Splits 變數宣告了卻沒用到;用 try/catch 包住跳轉也沒有實質意義,因為 location.href 賦值失敗並不會丟例外。
如果希望搜尋引擎知道行動版的存在,可在頁首加上:
<meta http-equiv="mobile-agent" content="format=xhtml; url=https://m.jb51.net" /> <meta http-equiv="mobile-agent" content="format=html5; url=https://m.jb51.net" />
意思是告訴搜尋引擎的行動版爬蟲該去抓哪個網址。
以 userAgent 判斷裝置的做法,在今日的網站開發中已被強烈不建議,原因有三:
第一,UA 字串正在消失。Google 主推的 User-Agent Reduction 計畫已逐步凍結 UA 中的版本號與平台細節,Chrome 也在推動以 Client Hints 取代 UA。單靠 UA 字串判斷會越來越不可靠。
第二,UA 可被任意偽裝。使用者可透過擴充套件或開發者工具改寫 UA,平板也可能回報桌面版 UA(iPadOS 的 Safari 預設就自稱 Macintosh)。
第三,對 SEO 有害。Google 明確建議改用「響應式網頁設計」(RWD)——同一個 URL 提供同一份 HTML,靠 CSS media query 調整版面。做 m. 子網域跳轉時,若沒有正確設定 canonical 與 alternate 標籤,容易被判定為內容重複;而依 UA 動態送出不同 HTML(dynamic serving)則必須精準設定 Vary: User-Agent 標頭,做錯就會傷到排名。
優先採用響應式設計,讓版面自己適配:
/* 行動優先:預設樣式為手機 */
.container { width: 100%; }
@media (min-width: 768px) {
.container { max-width: 720px; margin: 0 auto; }
}
若確實需要執行期的裝置判斷(例如調整影片畫質),改用 Client Hints:
// 需伺服器先回傳 Accept-CH 標頭
if (navigator.userAgentData) {
const mobile = await navigator.userAgentData.mobile;
console.log('是否行動裝置:', mobile);
}
而單純只是「行動裝置要載入較輕的資源」,用 media query 搭配 picture 元素與 srcset 會比 JS 判斷更準也更早生效。
希望這份整理對你有所幫助。