繁体   English   中英

基于navigator.userAgent的Javascript重定向

[英]Javascript redirect based on navigator.userAgent

我正在尝试重定向用户,当他们访问基于他们正在使用的设备到相关应用商店的网页时:

  //iPhone Version:
     if((navigator.userAgent.match(/iPhone/i)) ||  (navigator.userAgent.match(/iPod/i))) {
        window.location.href = "https://itunes.apple.com/gb/app/APP123";
      }

  //Android Version:
     if(navigator.userAgent.match(/android/i)) {
        window.location.href = "https://play.google.com/store/apps/details?id=com.APP.123";
       }
   //Anything Else  
     else {
        window.location.href = "https://example.com";
       }

这完全适用于iPhone以外的所有功能。

我知道userAgent会检测到iPhone部件,但它会忽略重定向到Apple App Store并重定向到example.com

任何建议都会受到很大的关注

您需要使用else if ,而不只是if

if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i)) {
  window.location.href = "https://itunes.apple.com/gb/app/APP123"
} else if (navigator.userAgent.match(/android/i)) {
  window.location.href = "https://play.google.com/store/apps/details?id=com.APP.123"
} else {
  window.location.href = "https://example.com"
}

如果你不使用else if块,那么你将有2个if语句:

  • 一个检查它是否是一个iPhone,否则什么都不做(因为没有else阻止)
  • 另一个检查它是否是Android,否则重定向到https://example.com

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM