場景描述:當在小程序中打開h5頁面時,希望小程序的轉發出去的標題,圖片,跳轉link可以通過h5通信實現自定義。
實現方式:通過h5給小程序通信,發送標題,圖片,跳轉link等信息,讓小程序設置分享。
- h5發送給小程序通信代碼
引用微信js1.3.2以上才支持,<script type="text/javascript" src="//res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>
判斷h5是在小程序環境中打開代碼:
//判斷是否是小程序環境 function doMiniProgram(callback) { try { //小程序環境設置分享 var ua = window.navigator.userAgent.toLowerCase(); //判斷是否是微信環境 if (ua.match(/MicroMessenger/i) == 'micromessenger') { //微信環境 wx.miniProgram.getEnv(function (res) { if (res.miniprogram) { callback(); } }) } } catch (ex) { console.log(ex); } }
給小程序發送數據設置小程序分享:
//設置小程序分享 function setMiniProgramShare(shareTitle, imageUrl, shareUrl) { try { doMiniProgram(function () { // 小程序環境下邏輯 wx.miniProgram.postMessage({ data: { title: shareTitle, path: shareUrl, imageUrl: imageUrl } }) }); } catch (ex) { console.log(ex); } }
- 小程序接收&處理邏輯
h5頁面: <web-view src="{{url}}" bindmessage="message"/>
js邏輯:
Page({ data: {shareData:{}}, onShareAppMessage(options) { return this.shareData }, message (e) { var that = this console.log(e) that.shareData = e.detail.data[0] } })