1.跳转后页面还存在的原因
- H5端调用
uni.reLaunch之后之前页面栈会销毁,但是无法清空浏览器之前的历史记录,此时navigateBack不能返回,如果存在历史记录的话点击浏览器的返回按钮或者调用history.back()仍然可以导航到浏览器的其他历史记录。
2.跳转后,在跳转后的页面里,加载方法
javascript
onLoad(option) {
// #ifdef H5
this.initPreventBack();
// #endif
},
javascript
methods: {
initPreventBack() {
// 禁用浏览器返回按钮
history.pushState(null, null, document.URL);
window.addEventListener('popstate', this.handlePopState);
// 禁用手势返回(左右边缘都监听)
document.addEventListener('touchstart', this.handleTouchStart, {
passive: false
});
document.addEventListener('touchmove', this.handleTouchMove, {
passive: false
});
},
removePreventBack() {
window.removeEventListener('popstate', this.handlePopState);
document.removeEventListener('touchstart', this.handleTouchStart);
document.removeEventListener('touchmove', this.handleTouchMove);
},
handlePopState() {
history.pushState(null, null, document.URL);
this.showPreventToast();
},
handleTouchStart(e) {
// 记录触摸起始位置
this.startX = e.touches[0].clientX;
},
handleTouchMove(e) {
if (!this.startX) return;
const currentX = e.touches[0].clientX;
const screenWidth = window.innerWidth;
// 检测边缘滑动(左右各10px范围内)
const isEdgeSwipe = this.startX < 10 || this.startX > screenWidth - 10;
// 检测滑动方向(防止误触)
const isBackSwipe = Math.abs(currentX - this.startX) > 30;
if (isEdgeSwipe && isBackSwipe) {
e.preventDefault();
this.showPreventToast();
}
},
showPreventToast() {
uni.showToast({
title: '跳转完成,退出程序!',
icon: 'none',
duration: 2000
});
}
}