监测浏览器返回事件并弹窗提示
背景:pm要求在进入到当前页面后,用户点击浏览器返回按钮,弹出对话框提示当前页面内容的必要性
vue代码片段:
import { Dialog } from 'vant';
... ...
handleAddConfirmBack () {
const STATE = {
TITLE: document.title,
URL: window.location.pathname + window.location.search
};
window.history.pushState(STATE, STATE.TITLE, STATE.URL);
function confirm (e) {
e.stopPropagation();// 阻止事件传播
Dialog.confirm({
title: '',
message: '根据相关规定,一下内容必须填写',
'confirmButtonText': '继续',
'cancelButtonText': '返回'
}).then(() => {
window.history.pushState(STATE, STATE.TITLE, STATE.URL);
}).catch(() => {
window.history.go(-1);
});
}
window.addEventListener('popstate', confirm, false);
this.$once('hook:beforeDestroy', function () {
window.removeEventListener('popstate', confirm);
});
}