vue 返回拦截



data() {
return {

// 返回拦截相关
interceptCount: 0,
maxInterceptCount: 2,
isInterceptionActive: false,
popStateHandler: null,
};
},

js

// 为homePop弹窗设置返回拦截
setupHomePopBackInterception() {
// 仅在H5环境下执行
if (typeof window !== 'undefined') {
// 重置拦截计数器
this.interceptCount = 0;
this.isInterceptionActive = true;
console.log('设置返回拦截,最大次数:', this.maxInterceptCount);

// 移除旧的监听器,防止重复绑定
if (this.popStateHandler) {
window.removeEventListener('popstate', this.popStateHandler);
}

// 添加历史记录,用于拦截
window.history.pushState({key: Date.now()}, '', window.location.href);

// 绑定popstate事件
this.popStateHandler = (e) => {
this.handleHomePopPopState(e);
};
window.addEventListener('popstate', this.popStateHandler);
}
},

// 移除homePop弹窗的返回拦截
removeHomePopBackInterception() {
if (typeof window !== 'undefined' && this.popStateHandler) {
window.removeEventListener('popstate', this.popStateHandler);
this.popStateHandler = null;
this.isInterceptionActive = false;
console.log('移除返回拦截');
}
},

// 处理返回事件
handleHomePopPopState(e) {
if (!this.isInterceptionActive || this.PopupWidgetType !== 0) {
return;
}

this.interceptCount++;
console.log('拦截返回事件,第', this.interceptCount, '次');

// 检查是否达到最大拦截次数
if (this.interceptCount <= this.maxInterceptCount) {
// 阻止默认返回行为
window.history.pushState({key: Date.now()}, '', window.location.href);

// 确保弹窗显示
if (this.$refs.homePop) {
console.log('显示弹窗');
this.$refs.homePop.open();

// 双重确保:通过DOM操作直接显示弹窗
setTimeout(() => {
const popupEl = document.querySelector('.PopupWidget');
if (popupEl) {
popupEl.style.display = 'block';
popupEl.classList.add('uni-popup--show');
}
}, 10);
}
} else {
// 达到最大拦截次数,移除拦截
console.log('达到最大拦截次数,允许返回');
this.removeHomePopBackInterception();
}
},


onUnload() {
// #ifdef H5
window.removeEventListener('message', this.handleWebviewMessage);
// #endif
// 确保移除返回拦截监听器
// 移除homePop弹窗的返回拦截
this.removeHomePopBackInterception();
this.onPageUnload();
// 确保移除DcWidget的返回拦截
if (this.onPageUnload) {
this.onPageUnload();
}
},

// 页面隐藏时移除事件监听器
onHide() {
// 页面隐藏时移除返回拦截
// 移除homePop弹窗的返回拦截
this.removeHomePopBackInterception();
this.onPageHide();
// 确保移除DcWidget的返回拦截
if (this.onPageHide) {
this.onPageHide();
}
},
// 页面显示时重新绑定返回拦截
// 页面显示时设置返回拦截
async onShow() {
await this.getUserInfo();
this.getBannerUrl();
this.getVipBenefit();
if (this.PopupWidgetType == 0) {
// 显示homePop弹窗
// PopupWidgetType为0时,使用homePop弹窗和自定义返回拦截
setTimeout(() => {
if (this.$refs.homePop) {
this.$refs.homePop.open();
// 设置返回拦截
// this.$refs.homePop.open();
// 设置homePop弹窗的返回拦截
this.setupHomePopBackInterception();
}
}, 500);
// 确保此时不启用DcWidget的返回拦截
if (this.removeBackInterception) {
this.removeBackInterception();
}
} else {
// 移除返回拦截
// PopupWidgetType不为0时,使用DcWidget的返回拦截
// 移除homePop弹窗的返回拦截
this.removeHomePopBackInterception();
}
// 绑定返回拦截
this.onPageShow();
// 启用DcWidget的返回拦截
if (this.onPageShow) {
this.onPageShow();
}
}
},
};

posted @ 2025-11-05 09:40  Bashuslovakia  阅读(24)  评论(0)    收藏  举报