搞死人了啦
1. JS拦截浏览器回退(坑)
需求:对方表单页面填写完跳转到我们的详情页面,当点击返回时需注意不要再返回到对方页面,直接回退到我们的首页或者服务记录页面。(需要注意浏览器默认事件,以及安卓左滑返回等情况)
// created -- 添加 popstate 事件监听
window.history.pushState(null, null, window.location.href);
window.addEventListener('popstate', this.onPopState);
// beforeDestroy -- 在组件销毁前,移除 popstate 事件监听
window.removeEventListener('popstate', this.onPopState)
// methods
onPopState(event){
window.history.pushState(null, null, window.location.href);
// this.isBack: true 点击返回按钮、false 浏览器默认事件|左滑
// params.from: orderListKc 表示从服务记录页面进入
let params = JSON.parse(decodeURIComponent(window.atob(window.location.href.split('?')[1])));
if(params.from === "orderListKc"){
window.history.go(-1)
}else{
window.location.href = window.location.href.includes("yjadmin.youjiajk.com") ? `https://health.youjiajk.com/h5/#/mine/index`:`https://www.youjiajktest.com/h5/#/mine/index`;
return;
}
}
popstate 首次进入页面不触发,需要用户和浏览器有交互才会触发拦截效果,比如用户点击弹窗、按钮、或者页面任意位置,才会生效。
2. JSON.parse(str); 异常
用倒推法先检查 str 是否为完整对象,很大概率 str 异常,排错时发现 str 是从 this.$route.query 中取的,该方法取路由参数,碰到“#”号时会被截断,只能获取到#号以前的字符串,所以 JSON.parse() 报错。 `
const { type, storeItem, user, mapInfo, number } = this.$route.query;
const item = JSON.parse(storeItem); // 报错
`