前言
在h5中使用navigateBack回退到微信小程序頁面很常見,但是有一種交互需要在回退之后的頁面可以得到通知,拿到標識之后,進行某些操作,這樣的話,由于微信官方并沒有直接提供這樣的api,就需要我們開動腦筋曲線救國一下:navigateBack +?postMessage
前置資源引入jssdk
微信端
在需要調用JS接口的頁面引入如下JS文件:http://res.wx.qq.com/open/js/jweixin-1.6.0.js (支持https)
如需進一步提升服務穩定性,當上述資源不可訪問時,可改訪問:http://res2.wx.qq.com/open/js/jweixin-1.6.0.js (支持https)
備注:支持使用 AMD/CMD 標準模塊加載方法加載。
<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
支付寶端
支付寶小程序可以使用 webview 承載一個 H5 頁面,但是不能在 webview 中直接調起支付,需要引入支付寶的??https://appx/web-view.min.js?(此鏈接僅支持在支付寶客戶端內訪問)文件。
<script>if (navigator.userAgent.indexOf('AlipayClient') > -1) {document.writeln('<script src="https://appx/web-view.min.js"' + '>' + '<' + '/' + 'script>')}</script>
核心代碼
H5頁面
// 方法封裝
export function navigateBackJumpParams(paramObj) {if (typeof window.my !== 'undefined') {// 支付寶小程序window.my.postMessage({data: JSON.stringify(paramObj)})window.my.navigateBack({ delta: 1 })} else {// 小程序window.wx.miniProgram.postMessage({data: JSON.stringify(paramObj)})window.wx.miniProgram.navigateBack({ delta: 1 })}
}// 場景觸發const paramObj = {couponSelectFlag: false,pageFromKey: "confirmOrderCouponListKey"}navigateBackJumpParams(paramObj)
1、支付寶小程序使用window.my對象;微信小程序使用window.wx.miniProgram對象
2、發送消息的方式是調用postMessage
方法,該方法接受一個對象作為參數,參數必須使用固定字段【data】;paramObj
?必須是一個 JavaScript 對象,否則無法使用?JSON.stringify
?函數將其轉換為 JSON 字符串。
3、回退到當前小程序頁面是調用navigateBack
函數,該方法接受一個對象作為參數,delta表示返回的頁面數,如果 delta 大于現有頁面數,則返回到首頁。
微信項目中
承載網頁的容器 - web-view
// template
<web-viewwx:if="{{ url }}"src="{{ url }}"bindmessage="getMessageFromHTML"binderror="handleWebViewError"
></web-view>// methods
async getMessageFromHTML(e) {if(e.detail?.data) {const postMessageInfo = Array.isArray(e.detail.data)? e.detail.data[0] || '': e.detail.data || ''let postMessageInfoParse = {}try {postMessageInfoParse = postMessageInfo ? JSON.parse(postMessageInfo) : {}} catch (error) {postMessageInfoParse = postMessageInfo}// 獲取與h5頁面商定的事件名稱邏輯if(postMessageInfoParse.pageFromKey === 'confirmOrderLslCouponList' && postMessageInfoParse.couponSelectFlag) {EventBus.emit('confirmOrderLslQueryEstimate', {couponSelectLslFlag: true})return}
}
使用頁面的監聽
// confirmOrderLslQueryEstimate是web-view發出的事件名稱
async attached() {EventBus.on('confirmOrderLslQueryEstimate', (data) => {// doing 監聽到該事件時,頁面具體做的操作})
}// 組件的頁面生命周期-監聽頁面卸載
detached() {EventBus.un('confirmOrderLslQueryEstimate')
},