[fix]: ctx `addInitScript` on popup pages
Merged
SE
10mo ago+255+255+012345678901234567890123456789-78-78-01234567890123456789
why
- fixes #1628
- scripts injected via
context.addInitScript()were not reliably applied to pages that were created via a popup (eg, clicking a link that opens a new page), or, when a new page was created viacontext.newPage(url). - when a target was created directly at a URL, navigation often started before attaching to the target & installing the init script. this means that the script would either run too late or not run at all.
what changed
- enabled
waitForDebuggerOnStartinTarget.setAutoAttachincdp.ts, so that new targets pause until we explicitly resume them - in
understudy/context.ts:onAttachedToTarget()now installs context init scripts on the session before resuming, then resumes withRuntime.runIfWaitingForDebugger. this guarantees scripts are registered before the first real document executes.- worker targets are resumed immediately. we still are not attaching to them, but they need to be resumed since we are now telling everything to wait for the debugger.
- added
seedOnlytoapplyInitScriptsToPage()so thepageobject records scripts without re‑installing them newPage()first creates targets atabout:blankand then navigates after attach (fire‑and‑forget). this avoids the race where the first document loads before init scripts are installed
- in
understudy/page.ts, i addedseedInitScript()so thepagecan track scripts that were already installed on the session
test plan
- added additional tests to
tests/context-addInitScript.spec.tswhich explicitly coverscontext.newPage(url)and popup pages to ensure init scripts run on the initial document
Summary by cubic
Fixes a race where context.addInitScript() didn’t run on the first document for new pages opened via popups or context.newPage(url). New targets now pause until init scripts are registered, ensuring scripts run reliably.
- Bug Fixes
- Paused new targets with waitForDebuggerOnStart; resume after script install.
- Installed init scripts on the CDP session before first document executes.
- Resumed worker targets immediately so they don’t stay paused.
- Created newPage() at about:blank, attach, then navigate (fire-and-forget).
- Seeded scripts/URL on Page to avoid double installs and timing issues.
- Added tests for newPage(url) and popup pages to verify scripts run on initial load.