問題描述
如果本地安裝了app那么直接打開,否則蘋果要跳轉到app-store,安卓則要跳到對應的市場
解決方案 一
//html代碼中 的 a 標簽,以微信為例,默認的是調用weixin scheme,去打開本機的微信,如果沒有則跳轉到相應連接
<a href="weixin://" 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比可以,結果自行實驗。(ios就是強大)
后續繼續研究中......