Skip to content

fix(context): reuse the session of an attached target in attach_target - #668

Merged
route merged 1 commit into
mainfrom
fix/attach-target-idempotent
Oct 21, 2026
Merged

route merged 1 commit into
mainfrom
fix/attach-target-idempotent

Conversation

@route

@route route commented Oct 21, 2026

Copy link
Copy Markdown
Member

Context#attach_target on a target that already had a session opened another one. Chrome reported it through Target.attachedToTarget, so Ferrum treated it like an auto-attach: it re-armed auto-attach on the new session, which attached every worker again, registered the extensions again, so they ran once more per document, and overwrote target.session_id while the cached Page/Worker stayed on the first session.

Fix

  • attach_target returns the target as is when it already has a session, like Puppeteer's target.page()/target.worker() reuse the session they have.
  • It returns the Target instead of true, so browser.attach_target(id).worker works. A target is truthy, so callers checking the result keep working.
  • Ferrum never handled Target.detachedFromTarget, so a detached target kept a dead session_id and the early return would have skipped the attach. The session id is now cleared on Target.detachedFromTarget, and right away when Ferrum lets go of a service worker, so attach_target right after the worker shows up doesn't pick the session that is about to be detached.

Test

  • spec/context_spec.rb: attaching twice to a page with an extension returns the target, keeps its session and the extension runs once after a reload. Without the fix the session changes and the extension runs three times.
  • spec/worker_spec.rb: a detached service worker target has no session id.

attach_target on a target with a session opened another one, which Ferrum handled like an auto-attach: workers
were attached again, extensions ran once more per document and target.session_id moved away from the cached page.

Return the target when it already has a session, and return the target instead of true. Clear the session id on
Target.detachedFromTarget and when a service worker is let go, so detached targets can be attached again.
@route
route merged commit 37f10c5 into main Oct 21, 2026
6 checks passed
@route
route deleted the fix/attach-target-idempotent branch October 21, 2026 17:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant