2019年11月26日 星期二

判斷上網設備(手機,桌機),並動態導向至可不同網頁

◆ 程式目的: 判斷上網設備(手機,桌機)並動態導向至不同網頁

◆ 注意事項: 以下程式必須放在HTML head > meta > titile 之後的第一時間執行

◆ split("/")技術細節說明

  ※web url sample: https://a.b.c/web_root/language/real_root/sub_folder
  ※web_root == folder of: desktop, mobile, ftp, ...
  ※language == en, tw, cn, ...
  ※real_root == index.html, index.php, folder name of project, css, imgs, js, ...
  
  aUrl[0] == https:
  aUrl[1] == null
  aUrl[2] == a.b.c
  aUrl[3] == web_root
  ...

◆ Javascript Source Code
<script>
  // web url sample: https://a.b.c/web_root/language/real_root/sub_folder
  var sOriginUrl = document.URL;
  var aUrl = sOriginUrl.split("/");

  if (aUrl[3] === "desktop" && (aUrl[4] === "" || typeof aUrl[4] == "undefined")){
    window.location = "/desktop/<language>";
  } else if (aUrl[3] === "mobile" && (aUrl[4] === "" || typeof aUrl[4] == "undefined")){
    window.location = "/mobile/<language>";
  }

  var gotoNewWebLocation = function() {
    var w = window,
      d = document,
      b = d.getElementsByTagName("body")[0],
      e = d.documentElement,
      x = e.clientWidth || b.clientWidth,
      y = e.clientHeight || b.clientHeight;
    
    // 舊手機規格以「768px-1」為判斷依據。Bootstrap 4 已改為「1200px-1」
    // 本人建議,仍須考量幾個手機螢幕規格的判斷點:
    //     1440x810, 1600x900, 1920x1080, 2560x1440
    // 其中,以 1920 x 1080 為門檻(人類視覺只要超過1920px就無法分辨出差別)
    
    // 注意 n == 所要判斷字串的字數,若是en, tw 則是 2
    if (x <= 767) { // or 1079
      if (aUrl[3] == "desktop" && aUrl[4].substr(0,n) == "<language>" ) window.location = "/mobile/<language>";
    } else {
      if (aUrl[3] == "mobile" && aUrl[4].substr(0,n) == "<language>") window.location = "/desktop/<language>";
    }
  };
  gotoNewWebLocation();
  
  if (window.addEventListener) {
    window.addEventListener("resize", gotoNewWebLocation);
    window.addEventListener("orientationchange", gotoNewWebLocation);
  } else if (window.attachEvent) { // 相容IE事件
    window.attachEvent("onresize", gotoNewWebLocation);
  }
</script>