关于监听微信浏览器返回按钮事件处理安卓IOS通用

阎小妍

关注

阅读 113

2022-05-10


1.效果

关于监听微信浏览器返回按钮事件处理安卓IOS通用_vue

效果说明:

  1. 做了个dialog组件,打开编辑联系人,可以通过物理返回键关闭这个dialog,这里原本物理返回是会返回上一页的
  2. 返回上一页,即退出报名页,这里监听了物理返回,确定才正式返回上一页
  3. 以上功能在安卓和ios上测试都通过

代码

methods

windowListener() {
let that = this;
if(this.userEditType == 1 && this.addPersonFlag && this.isShowUserEdit){//点击返回的时候,满足联系人dialog开启了的条件的就关闭dialog,阻止返回上一页
this.isShowUserEdit = false;
this.addPersonFlag = false;
that.pushHistory();
return
}
if (this.addPersonFlag && !this.isShowUserEdit) {//根据条件关闭dialog,阻止返回上一页
this.addPersonFlag = false;
that.pushHistory();
return;
}
if (this.addPersonFlag && this.isShowUserEdit) {//根据条件关闭dialog,阻止返回上一页
this.isShowUserEdit = false;
this.addPersonFlag = true;
that.pushHistory();
return;
}
if (!this.addPersonFlag && !this.isShowUserEdit) {//dialog都关闭的,点了返回,看用户是否真的要返回
weui.confirm("确定要取消报名吗?", {
title: "提示",
buttons: [
{
label: "取消",
type: "default",
onClick: function() {//不返回,就阻止原生返回
that.pushHistory();
}
},
{
label: "确定",
type: "primary",
onClick: function() {//返回就返回到指定页面,注:推荐上一页是有规律的情况下使用,如果不是固定的,就用session记录pushHistory()执行的次数,返回到pushHistory()执行的次数的前一页才是正确的上一页这里就不多做解释
that.$router.replace({//跳转
path: `/app/act/${that.$route.query.iid}/detail_test/${
that.$route.query.actId
}?saleR=${
that.$route.query.saleR ? that.$route.query.saleR : ""
}&disrParentMultiDisKey=${
that.$route.query.disrParentMultiDisKey
? that.$route.query.disrParentMultiDisKey
: ""
}`
});
}
}
],
isAndroid: false
});
}
},
pushHistory() {//阻止返回上一页的方法,原理就是在历史记录里插上一条当前的页面
let state = {
title: "",
url: window.location.href
};
window.history.pushState(state, state.title, state.url);
},

mounted

this.pushHistory();
window.addEventListener("popstate", this.windowListener, false);//监听物理返回键

销毁监听

beforeDestroy() {
window.removeEventListener("popstate", this.windowListener);
},



精彩评论(0)

0 0 举报