1. 程式人生 > 其它 >uaredirect手機訪問網站轉向手機網站程式碼

uaredirect手機訪問網站轉向手機網站程式碼

雖然現在很多網站已經採用了多平臺自適應的網站,但是也還是有一些網站採用PC端和移動手機站分開的方式,這就需要在客戶通過手機訪問網站的時候,將訪問引導到手機站,以便客戶可以獲得更好的訪問體驗,例如我們想將https://www.zhaohespray.com 這個站,當客戶通過手機訪問的時候將域名轉向到https://m.zhaohespray.com. 通過什麼程式碼來達到最好的效果呢。

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}}}};
var location_url = 'https://m.zhaohespray.com';
var location_host = window.location.pathname;
var newUrl = location_url+location_host;
uaredirect(newUrl);

  當然,還有其他方法,也比較簡單,通過js判斷螢幕大小來實現轉向,如果螢幕小於728 就轉向到手機站。