前言:
h5分享到微信,h5使用微信支付這些功能,都需要先判斷是否安裝微信客戶端,如果已安裝就啟動微信,如果沒有安裝微信,就提示用戶前去安裝。
我們可以通過訪問微信提供的URL協議(weixin://)來實現這個功能,代碼如下:
示例代碼:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"> 6 <title>判斷手機是否安裝微信</title> 7 </head> 8 <body> 9 <a href="javascript:testApp('weixin://')" class="dl-btn" id="download">打開微信</a> 10 <script> 11 function testApp(url) { 12 var timeout, t = 1000, hasApp = true; 13 setTimeout(function () { 14 if (!hasApp) { 15 //沒有安裝微信 16 var r=confirm("您沒有安裝微信,請先安裝微信!"); 17 if (r==true){ 18 location.href="http://weixin.qq.com/" 19 } 20 }else{ 21 //安裝微信 22 } 23 document.body.removeChild(ifr); 24 }, 2000) 25 26 var t1 = Date.now(); 27 var ifr = document.createElement("iframe"); 28 ifr.setAttribute('src', url); 29 ifr.setAttribute('style', 'display:none'); 30 document.body.appendChild(ifr); 31 timeout = setTimeout(function () { 32 var t2 = Date.now(); 33 if (!t1 || t2 - t1 < t + 100) { 34 hasApp = false; 35 } 36 }, t); 37 } 38 </script> 39 </body> 40 </html>
擴展:
同樣,通過上邊的方法,也可以判斷是否安裝第三方app,前提是第三方app必須提供相應的URL協議,具體參考:H5外部瀏覽器直接調起App
后記:
看到有博友評論,貼了一百多行php前端后端的代碼,所以也就重新整理了下這篇文章。使用本文方法,關鍵代碼也就那么二十幾行,大部分瀏覽器都是能正常調起微信的,一般來說這已經足夠了。實在是不太明白為什么前端用js就能解決的問題還要搞一大堆php前端后端管理后台的東西,作為一個前端開發來說,實現一個功能自然是代碼越精簡越好,前端能實現的就盡量不要勞煩后端,h5能搞定的,就無需用什么php。