JS判断手机端是否安装某应用

时间:2021-09-07 18:28:02

方法一(网页上判断)

if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) {
  var loadDateTime = new Date();
  window.setTimeout(function() {
   var timeOutDateTime = new Date();
   if (timeOutDateTime - loadDateTime < 5000) {
    window.location = "要跳转的页面URL";
   } else {
    window.close();
   }
  },
  25);
  window.location = "www://?param1=xxx&param2=xxx ";//与APP约定的一个协议URL
 } else if (navigator.userAgent.match(/android/i)) {
  var state = null;
  try {
   state = window.open("www://?param1=xxx&param2=xxx ", '_blank');//与APP约定的一个协议URL
  } catch(e) {}
  if (state) {
   window.close();
  } else {
   window.location = "要跳转的页面URL";
  }
 }

方法二

function testApp(url) {
  var timeout, t = 1000, hasApp = true;
  setTimeout(function () {
    if (hasApp) {
      alert('安装了app');
    } else {
      alert('未安装app');
    }
    document.body.removeChild(ifr);
  }, 2000)
  
  var t1 = Date.now();
  var ifr = document.createElement("iframe");
  ifr.setAttribute('src', url);
  ifr.setAttribute('style', 'display:none');
  document.body.appendChild(ifr);
  timeout = setTimeout(function () {
     var t2 = Date.now();
     if (!t1 || t2 - t1 < t + 100) {
       hasApp = false;
     }
  }, t);
}

方法三(APP里判断)

var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android终端或者uc浏览器
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
 
if(isAndroid){
      function android(){
        window.location.href = "www://?param1=xxx&param2=xxx"; /***打开app的协议,有安卓同事提供***/
        window.setTimeout(function(){
           window.location.href = "http://"; /***下载app的地址***/
        },2000);
      };
if(isiOS){
      function ios(){
        var ifr = document.createElement("iframe");
        ifr.src = "www://?param1=xxx&param2=xxx"; /***打开app的协议,有ios同事提供***/
        ifr.style.display = "none";
        document.body.appendChild(ifr);
        window.setTimeout(function(){
          document.body.removeChild(ifr);
           window.location.href = "http://"; /***下载app的地址***/
        },2000)
      };
}