Files
aichat/src/utils/history-guard.ts
T
2026-10-16 21:39:08 +08:00

53 lines
2.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 页面处于隐藏状态时,拦截原生 `history.replaceState`。
*
* ── 起因 ────────────────────────────────────────────────────────────────
* vue-router 4.6.4 在创建 history 时**无条件**注册(源码见
* node_modules/vue-router/dist/vue-router.mjs 的 createRouterHistory,
* 不受是否配置 `scrollBehavior` 影响):
*
* document.addEventListener('visibilitychange', beforeUnloadListener)
*
* 该监听器在每次「切标签 / 最小化窗口 / 切到后台」时执行:
*
* if (document.visibilityState === 'hidden') {
* if (!history.state) return
* history.replaceState({ ...state, scroll: getScroll() }, '')
* }
*
* 而 Edge 对「文档处于 hidden 状态时写入 history」会做出反应 ——
* **把最小化的窗口拉回前台**。表现为:功能完全正常、无任何报错或日志,
* 但浏览器一最小化就立刻自动还原;无痕窗口不复现;换任何其他站点也不复现。
*
* 本项目并没有配置 `scrollBehavior`,这次写入完全无用,因此直接拦掉。
*
* ── 为什么拦在原语这一层,而不是拦 vue-router ───────────────────────────
* vue-router 的 `u()` 照常运行、照常调用 replaceState;被替换的只是
* `history.replaceState` 这个原生 API 本身 —— 最后一道边界。拦在原语上意味着
* 无论将来 vue-router 换实现,还是我们自己写了别的代码想在页面隐藏时改动
* history,都会被同样拦住。这才是要守住的规则本身:「页面不可见时不要改动
* 浏览器历史记录」。
*
* ── ⚠️ Phase 3 接入 CEF 前必须保留本文件 ────────────────────────────────
* CEF 窗口同样会跑 vue-router、同样会触发这条路径。桌面程序的窗口自己弹回
* 前台是严重缺陷,不是观感问题,所以这个修复是 Phase 3 的前置条件。
*
* 排查过程见 `.scratch/改造计划.md`。
*/
if (typeof window !== 'undefined' && typeof history !== 'undefined') {
const originalReplaceState = history.replaceState.bind(history)
history.replaceState = function patchedReplaceState(
state: Parameters<History['replaceState']>[0],
unused: Parameters<History['replaceState']>[1],
url?: Parameters<History['replaceState']>[2],
): void {
if (document.visibilityState === 'hidden') {
// 页面不可见时改动 history 会让 Edge 把最小化的窗口拉回前台
return
}
originalReplaceState(state, unused, url)
}
}