前言
最近做完公司官網,因為不是做的響應式,而是分別PC和mobile各寫了一套,所以有這樣一個需求:
識別用戶訪問設備,如果用戶通過電腦訪問,則跳轉至PC官網;反之通過手機訪問,則跳轉至mobile官網。
那應該怎么實現呢?
解決方法
查了很多方法,最終選擇了下面這種
<script type="text/javascript"> 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"; document.writeln("您的瀏覽設備為:"); if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) { document.writeln("phone"); } else { document.writeln("pc"); } } browserRedirect(); </script>
我自己稍微優化了一下代碼
//檢測移動端還是PC端登錄,分別跳轉到對應移動和PC官網 (function() { var sUserAgent = navigator.userAgent.toLowerCase(), bIsIpad = sUserAgent.match(/ipad/i) == "ipad", bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os", bIsMidp = sUserAgent.match(/midp/i) == "midp", bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4", bIsUc = sUserAgent.match(/ucweb/i) == "ucweb", bIsAndroid = sUserAgent.match(/android/i) == "android", bIsCE = sUserAgent.match(/windows ce/i) == "windows ce", bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile"; if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) { window.location.href = './mobile/index.html'; } else { window.location.href = './PC/index.html'; } })()
經測試,蘋果安卓手機,電腦瀏覽器均能正常實現根據不同設備訪問跳轉官網,iPad暫時沒測
一些思考
1. 和后端同事確認一下PC和mobile官網是各自用1個域名,還是共用1個域名分2個目錄,不同的訪問路徑
不同域名:比如 www.aa.com / www.bb.com
相同域名:比如 www.aa.com/pc / www.aa.com/mobile
不同域名直接根據上面js代碼跳轉至對應域名即可,相同域名有一些注意事項。
①:用戶輸入網站域名即可跳轉至官網,而無需手動輸入域名后的資源路徑。所以域名肯定不能回帶上路徑。
所以需要做一些操作。下面是后端同事發布代碼到服務器上的截圖,而相同域名下不能直接這樣,
需要在同級目錄下額外增加一個index.html文件,這個文件也要加入上面的js判斷代碼
根目錄如下
pc
mobile
index.html (包含js判斷代碼)
主要目的是根據用戶不同訪問設備跳轉至對應PC或mobile官網,這樣做的另一個好處就是用戶只需要輸入官網域名,
不需要帶上路徑,本來用戶需要輸入www.aa.com/pc或www.bb.com/mobile才能訪問對應官網,
現在用戶輸入www.aa.com就能直接訪問到對應官網,就是額外添加的同級目錄下的index.html文件幫忙實現的。
你可能會有個疑問,既然index.html中已經添加了js代碼判斷用戶訪問設備,那PC和mobile中的index.html中是否可以不加判斷?
答案是否定的。
如果用戶直接用電腦訪問mobile官網或用mobile設備訪問PC官網,你要不要給用戶跳轉官網?肯定是要跳轉的,
所以當出現此類情況,需要判斷用戶當前是否是用電腦或手機在訪問PC或mobile官網,如果不是,則需要給用戶跳轉回對應官網。
比如用戶用電腦訪問mobile官網,需要給用戶跳轉回PC官網,mobile相同。
②:另外需要注意的是,PC和mobile中index.html文件也都需要添加上面的js判斷代碼,但只需要一個判斷
同級目錄下index.html中的js判斷代碼

PC中index.html中js判斷代碼
mobile中index.html中js判斷代碼

有需要的朋友可以領取支付寶到店紅包,能省一點是一點