[fix]: ctx `addInitScript` on popup pages

Merged
SE
10mo ago
+255-78

why

  • fixes #1628
  • scripts injected viacontext.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 via context.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 waitForDebuggerOnStart in Target.setAutoAttach in cdp.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 with Runtime.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 seedOnly to applyInitScriptsToPage() so the page object records scripts without re‑installing them
    • newPage() first creates targets at about:blank and then navigates after attach (fire‑and‑forget). this avoids the race where the first document loads before init scripts are installed
  • inunderstudy/page.ts, i added seedInitScript() so the page can track scripts that were already installed on the session

test plan

  • added additional tests to tests/context-addInitScript.spec.ts which explicitly covers context.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.