瀏覽器和app沒有通信協議,所以h5不知道用戶的手機釋放安裝了app。因此只能是h5去嘗試喚起app,若不能喚起,引導用戶去下載我們的app。
微信里屏蔽了 schema 協議,如果在微信中打開h5,則會提示用戶在瀏覽器中打開。
HTML代碼
<div id="btn">
<a onclick="submitFn ><button>打開app</button></a>
</div>
js代碼
function submitFn(){
//判斷瀏覽器
var u = navigator.userAgent;
if(/MicroMessenger/gi.test(u) {
// 引導用戶在瀏覽器中打開
alert('請在瀏覽器中打開');
return;
}
var d = new Date();
var t0 = d.getTime();
if(u.indexOf('Android') > -1 || u.indexOf('Linux') > -1){
//Android
if(openApp('en://startapp')){
openApp('en://startapp');
}else{
//由於打開需要1~2秒,利用這個時間差來處理--打開app后,返回h5頁面會出現頁面變成app下載頁面,影響用戶體驗
var delay = setInterval(function(){
var d = new Date();
var t1 = d.getTime();
if( t1-t0<3000 && t1-t0>2000){
alert('請下載APP');
window.location.href = "app下載地址";
}
if(t1-t0>=3000){
clearInterval(delay);
}
},1000);
}
}else if(u.indexOf('iPhone') > -1){
//IOS
if(openApp('ios--scheme')){
openApp('ios--scheme');
}else{
var delay = setInterval(function(){
var d = new Date();
var t1 = d.getTime();
if( t1-t0<3000 && t1-t0>2000){
alert('請下載APP');
window.location.href = "app下載地址";
}
if(t1-t0>=3000){
clearInterval(delay);
}
},1000);
}
}
}
function openApp(src) {
// 通過iframe的方式試圖打開APP,如果能正常打開,會直接切換到APP,並自動阻止a標簽的默認行為
// 否則打開a標簽的href鏈接
var ifr = document.createElement('iframe');
ifr.src = src;
ifr.style.display = 'none';
document.body.appendChild(ifr);
window.setTimeout(function(){
document.body.removeChild(ifr);
},2000);
}
