前言
大家在日常開發的時候,經常會遇到這樣的需求,通過檢測手機,如果本地安裝了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比可以,結果自行實驗。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。
新聞熱點
疑難解答
圖片精選