监听浏览器路由

210 阅读1分钟

由于浏览器没有对pushState和replaceState事件的监听,所以在监听浏览器变化的时候,需要给事件添加监听 以下是使用TypeScript实现的重新编写pushState和replaceState的示例代码:

type State = {
  [key: string]: any;
};
const pushState = window.history.pushState;
window.history.pushState = function(state: State, title: string, url?: string | null): void {
  pushState.apply(window.history, [state, title, url]);
  const event = new Event('pushstate');
  event.state = state;
  event.title = title;
  event.url = url;
  window.dispatchEvent(event);
};

const replaceState = window.history.replaceState;
window.history.replaceState = function(state: State, title: string, url?: string | null): void {
  replaceState.apply(window.history, [state, title, url]);
  const event = new Event('replacestate');
  event.state = state;
  event.title = title;
  event.url = url;
  window.dispatchEvent(event);
};

window.addEventListener('pushstate', function(event: Event) {
  console.log('pushstate event', event);
});
window.addEventListener('replacestate', function(event: Event) {
  console.log('replacestate event', event);
});

以上代码对window.history.pushState和window.history.replaceState进行了类型定义,并重写了这两个方法以发出自定义事件。同时,使用Event类型定义了我们在事件监听器中接收的事件参数类型。最后,我们将自定义事件作为参数传递给了addEventListener函数中,以捕获这些事件并执行某些操作。 请注意,在TypeScript中使用apply函数时需要显式传递函数参数类型集合。