@yiero/gmlib
Version:
GM Lib for Tampermonkey/ScriptCat
71 lines (70 loc) • 2.04 kB
TypeScript
import type { RouteChangeCallback, Unsubscribe } from './types/RouteChange';
export type { IRouteChangeEvent, NavigationType, RouteChangeCallback, Unsubscribe, } from './types/RouteChange';
/**
* 监听页面路由变化
*
* 统一监听页面路由变化,支持:
* - `history.pushState` 调用
* - `history.replaceState` 调用
* - 浏览器前进/后退(popstate)
* - hash 变化(hashchange)
*
* **浏览器兼容性**:
* - 现代浏览器使用 Navigation API(Chrome 102+)
* - 降级方案:重写 history 方法 + 事件监听
*
* **单例模式**:只允许一个监听器存在,新调用会替换之前的监听器。
*
* **恢复机制**:调用 Unsubscribe 会恢复原始的 history 方法。
*
* @param callback 路由变化时的回调函数
* @returns 取消监听并恢复原始方法的函数
*
* @example
* // 基本用法
* const unsubscribe = onRouteChange((event) => {
* console.log('路由变化:', event.type);
* console.log('从:', event.from);
* console.log('到:', event.to);
* });
*
* @example
* // 根据导航类型处理
* const unsubscribe = onRouteChange((event) => {
* switch (event.type) {
* case 'push':
* console.log('pushState 导航');
* break;
* case 'replace':
* console.log('replaceState 导航');
* break;
* case 'traverse':
* console.log('前进/后退');
* break;
* case 'hash':
* console.log('hash 变化');
* break;
* }
* });
*
* @example
* // 拦截导航(仅 Navigation API 支持)
* const unsubscribe = onRouteChange((event) => {
* if (event.intercept) {
* event.intercept(async () => {
* // 自定义导航处理
* await loadPage(event.to);
* });
* }
* });
*
* @example
* // 取消监听
* const unsubscribe = onRouteChange((event) => {
* handleRouteChange(event);
* });
*
* // 之后取消监听
* unsubscribe();
*/
export declare function onRouteChange(callback: RouteChangeCallback): Unsubscribe;