Skip to content

🐛 修复 window.focus 窗口聚焦并加强 windowId 校验#1577

Open
cyfung1031 wants to merge 2 commits into
scriptscat:mainfrom
cyfung1031:codex/fix-1571-window-focus
Open

🐛 修复 window.focus 窗口聚焦并加强 windowId 校验#1577
cyfung1031 wants to merge 2 commits into
scriptscat:mainfrom
cyfung1031:codex/fix-1571-window-focus

Conversation

@cyfung1031

@cyfung1031 cyfung1031 commented Jul 12, 2026

Copy link
Copy Markdown
Collaborator

Checklist / 检查清单

  • Fixes API Compatibility Issue (GM/TM/VM)
  • Code reviewed by human / 代码通过人工检查
  • Changes tested / 已完成测试

背景

Tampermonkey 的 window.focus() 会激活脚本所在标签页,并将其所在的浏览器窗口置于前台。ScriptCat 原实现只激活标签页;当目标窗口处于后台时,浏览器窗口不会被带到前台,因此与 Tampermonkey 的行为不兼容。

另外,部分标签页相关流程可能取得无效的 windowId(例如负数窗口 ID)。若直接传给窗口聚焦或截图 API,可能触发异常或产生不明确的行为。

Fixes #1571

本次改动

window.focus() GM API

  • 保留 chrome.tabs.update(tabId, { active: true }),激活脚本所在标签页;
  • windowId 为有限且非负的有效值时,调用 chrome.windows.update(windowId, { focused: true }),将标签页所在窗口置于前台;
  • 无效 windowId 不再传入 chrome.windows.update()

Agent 标签页与截图流程

  • tab_tools.ts:聚焦标签页所在窗口前,增加有限且非负的 windowId 校验;
  • dom.ts:调用 chrome.tabs.captureVisibleTab() 前校验标签页和 windowId,无效时抛出明确错误。

测试

  • 新增 window.focus() 回归测试,验证标签页激活和浏览器窗口聚焦都会执行。

根因

原实现只调用 chrome.tabs.update(tabId, { active: true })。激活标签页不会自动将其所在的后台浏览器窗口置于前台,因此缺少窗口级聚焦调用。

同时,仅依赖 truthy 或有限数值判断不足以排除负数窗口 ID,需要统一要求 windowId 为有限且非负的值。

验证记录

  • pnpm exec vitest run src/app/service/service_worker/gm_api/gm_api.test.ts --reporter=default — 23 tests passed
  • pnpm run typecheck — passed
  • pnpm exec prettier --check src/app/service/service_worker/gm_api/gm_api.ts src/app/service/service_worker/gm_api/gm_api.test.ts — passed
  • pnpm exec eslint src/app/service/service_worker/gm_api/gm_api.ts src/app/service/service_worker/gm_api/gm_api.test.ts — passed
  • git diff --check — passed

Screenshots / 截图

Not applicable.

@cyfung1031 cyfung1031 marked this pull request as ready for review July 12, 2026 11:15
@cyfung1031 cyfung1031 changed the title 🐛 修复 window.focus 无法将浏览器窗口置于前台 🐛 修复 window.focus 窗口聚焦并加强 windowId 校验 Jul 12, 2026
@cyfung1031 cyfung1031 added the GM API 支持一下TM/VM/FM的API label Jul 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

GM API 支持一下TM/VM/FM的API

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Compatibility with Tampermonkey's window.focus

1 participant