/**
* 重写history的pushState和replaceState
* @param action pushState|replaceState
* @return {function(): *}
*/
const wrapEventHandle = (action) => {
// 获取pushState或replaceState方法
const handle = history[action];
return function () {
// 经过包装的pushState或replaceState
const wrapper = handle.apply(this, arguments);
// 定义名为action的事件
const e = new Event(action);
// 将调用pushState或replaceState时的参数作为state属性放到事件参数event上
e.state = { ...arguments, target: this };
// 调用pushState或replaceState时触发该事件
window.dispatchEvent(e);
return wrapper;
};
};
main.js写入全局弹窗
import ReactDom from 'react-dom';
const ROUTER_LIST = []; // 包含配置的路由地址才弹窗
let dive: any = null;
const body = document.body || document.documentElement;
const dialog = () => {
const { pathname } = window.location;
const flag = ROUTER_LIST.includes(pathname);
// 业务逻辑
// ...
dive = document.createElement('div');
body.appendChild(dive);
ReactDom.render(<DialogComp />, dive);
};
isVnADialog(); // 初始刷新调用一次
// 修改原始定义
history.pushState = wrapEventHandle('pushState');
history.replaceState = wrapEventHandle('replaceState');
// 监听自定义的事件
window.addEventListener('pushState', (e: any) => {
// console.info('pushState', e.state);
if (e.state) {
body.contains(dive) && body.removeChild(dive);
dialog();
}
});
window.addEventListener('replaceState', (e: any) => {
// console.info('replaceState', e.state);
if (e.state) {
body.contains(dive) && body.removeChild(dive);
dialog();
}
});