首先需要在应用中已经设置了scheme,IOS需在项目配置及页面配置中设置scheme,Android在清单文件中配置如下代码:
<activity
android:name=".activity.SplashActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE" />
<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="与后台约定的名字,必须" android:host="可以不设置" android:path="可以不设置"/>
</intent-filter>
</activity>
在JS中调用:
<a class="btn" href="下载链接" id="openApp">下载APP</a>
<script type="text/javascript">
document.getElementById('openApp').onclick = function(e){
// 通过iframe的方式试图打开APP,如果能正常打开,会直接切换到APP,并自动阻止a标签的默认行为
// 否则打开a标签的href链接
var ifr = document.createElement('iframe');
if(navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)){
ifr.src = '与IOS约定的scheme';
}else if(navigator.userAgent.match(/android/i)){
ifr.src = '与Android约定的scheme(scheme://[host]:[port]([path]|[pathPrefix]|[pathPattern]))';
}
ifr.style.display = 'none';
document.body.appendChild(ifr);
setTimeout(function() {
document.body.removeChild(ifr);
},1000);
};
</script>
这种办法还有个小问题:
Android系统因为此时setTimeout方法无效,会直接调timeout里的函数,自动阻止a标签的默认行为没能实现,在调起本机应用的同时,也会调起下载链接,看网上有很多方法包括在app中使用scheme://host/path拼接出下载链接,试了之后都没用(测试发现scheme设成http后不能调起本机应用)。