需求:用戶試圖關(guān)閉或者返回的時(shí)候攔截,并彈出提示框。
uni-app的onBackPress只能攔截左上角的返回贤旷,物理按鍵和左滑返回?cái)r截不了广料,采用popState的方式。
methods:{
showBack(){
//檢測(cè)到返回再插一條
window.history.pushState(null, null, document.URL);
//攔截邏輯
}
},
mounted(){
//頁(yè)面加載后先插一條記錄
window.history.pushState(null, null, document.URL);
window.addEventListener("popstate", this.showBack(), false);
}幼驶,
//銷毀監(jiān)聽事件艾杏,不然會(huì)影響其他頁(yè)面
destroyed() {
window.removeEventListener("popstate", this.showBack, false);
},
注意事項(xiàng):
1.其他頁(yè)面的返回事件,要改為 history.back() ,不能是 uni.navigateBack()盅藻。
2.部分瀏覽器购桑,如果用戶進(jìn)入頁(yè)面啥也不干就返回,是監(jiān)聽不到的氏淑,最好是彈一個(gè)框勃蜘,讓用戶關(guān)閉從而產(chǎn)生交互。這個(gè)暫時(shí)找不到更好的辦法