前言大家在日常开发的时候,经常会遇到这样的需求,通过检测手机,如果本地安装了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比可以,结果自行实验。
总结以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。