實現效果:微信小程序頁面嵌套web-view點擊系統導航返回時進行彈窗處理
首先在web-view里是不可實現的(據我了解下來)
參考小程序文檔:page-container
大致邏輯:
1、page-container可實現頁面離開前攔截
2、由于web-view層級最高,導致page-container里彈窗展示不出來,可使用cover-view
來做彈窗,page-container
只做攔截作用
index.wxml:
<!-- page.wxml -->
<web-view src="https://www.baidu.com"/>
<page-containershow="{{showBackConfirm}}"bindbeforeleave="handleBackAttempt"bind:afterleave="resetInterceptor"
>
</page-container>
<cover-view wx:if="{{isIntercepting}}" class="evaluate"><cover-view class="content"><cover-view>您覺得本次服務怎么樣?</cover-view><cover-view class="star-list"><cover-image class="star" src="/assets/collect-block.png"></cover-image><cover-image class="star" src="/assets/collect-block.png"></cover-image><cover-image class="star" src="/assets/collect-block.png"></cover-image><cover-image class="star" src="/assets/collect-block.png"></cover-image><cover-image class="star" src="/assets/collect-block.png"></cover-image></cover-view><cover-view class="btns"><button bind:tap="cancelBack">取消</button><button bind:tap="confirmBack">已評價</button></cover-view></cover-view>
</cover-view>
index.js:
Page({data: {showBackConfirm: true,isIntercepting: false // 狀態鎖,防止重復觸發},// ? 核心攔截函數(修正導航欄返回不生效問題)handleBackAttempt() {if (!this.data.isIntercepting) {this.setData({showBackConfirm: true,isIntercepting: true // 加鎖}, () => {// 確保彈窗渲染完成wx.nextTick(() => {return false; // 必須返回 false 才能攔截});});}return false; // 雙重保險},// ? 用戶確認返回confirmBack() {this.setData({showBackConfirm: false}, () => {setTimeout(() => wx.navigateBack(), 50); // 確保彈窗關閉后再返回});},// ? 用戶取消返回cancelBack() {this.setData({showBackConfirm: true,isIntercepting: false // 解鎖});},// ? Android 物理返回鍵專項處理onBackPress() {if (!this.data.isIntercepting) {this.setData({showBackConfirm: true});return true; // 必須返回 true 才能攔截}return false;},// ? 阻止 iOS 右滑穿透(關鍵!)preventSwipe() {return; // 空函數阻止默認滑動},// ? 重置攔截狀態resetInterceptor() {this.setData({isIntercepting: false});}
})
代碼片段:https://developers.weixin.qq.com/s/As1z2uma8Q0i