欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

利用js判断手机是否安装某个app的多种方案

程序员文章站 2022-04-30 12:52:22
前言 大家在日常开发的时候,经常会遇到这样的需求,通过检测手机,如果本地安装了app那么直接打开,否则苹果要跳转到app-store,安卓则要跳到对应的市场,下面来给大家...

前言

大家在日常开发的时候,经常会遇到这样的需求,通过检测手机,如果本地安装了app那么直接打开,否则苹果要跳转到app-store,安卓则要跳到对应的市场,下面来给大家介绍几种解决的方案。

解决方案 一

//html代码中 的 a 标签,以微信为例,默认的是调用weixin scheme,去打开本机的微信,如果没有则跳转到相应连接
    <a href="weixin://" rel="external nofollow" class="btn-download">立即打开</a>
  
    // 为btn-download 绑定事件,如果在500ms内,没有解析到协议,那么就会跳转到下载链接 
     var appstore, ua = navigator.useragent;
  if(ua.match(/android/i)){ 
   appstore = 'market://search?q=com.singtel.travelbuddy.android';
  }
  if(ua.match(/iphone|ipod|ipad/)){
   appstore = "https://itunes.apple.com/cn/app/wei-xin/id414478124?mt=8&ign-mpt=uo%3d4"; 
  }
  function applink(fail){ 
   return function(){ 
    var clickedat = +new date; 
    // during tests on 3g/3gs this timeout fires immediately if less than 500ms. 
    settimeout(function(){ 
      // to avoid failing on return to mobilesafari, ensure freshness! 
      if (+new date - clickedat < 2000){ 
       window.location = fail; 
      } 
    }, 500);  
   }; 
  } 
  $('.icon-download, .btn-download')[0].onclick = applink(appstore);

解决方案二

通过在页面中生成一个隐藏的iframe,iframe的src指向 app 协议,例如 weixin scheme,并监听onerror事件,意思是如果无法解析协议,就会触发onerror事件,但是我尝试了一下,未果。代码如下,可参考一下。

// 页面中有div#iframe-box 用来插入生成的iframe,还是以微信为例
     var ifm = document.createelement('iframe'), isinstalled;
  ifm.style.display = 'none';
  ifm.src = 'wixin://';
  ifm.onload = function(e){
   var e = e || window.event;
   e.preventdefault();
  }
  ifm.onerror = function(){
   //isinstalled = false;
   alert(1);
  }
  document.getelementbyid('iframe-box').appendchild(ifm);

    // 但这时的问题是,iframe的src成功解析到了协议,则会直接跳转,但是解析不到的话,也不会触发error事件,这个还要继续研究
    // 可以把上面的代码,放到函数中,然后作为某个按钮的响应函数。

解决方案三

对于ios手机,会有如下写法

<meta name="apple-itunes-app" content="app-id=414478124" /> 

将上面代码放到head中,根据name也会知道意思,app-id是微信的app-id,用ios手机看会看到提示,andriod比可以,结果自行实验。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。