Playwright - Attaching to Webworker in existing chromium instance

4 days ago 5
ARTICLE AD BOX

I'm trying to connect to an existing chromium instance and attach to a WebWorker within that scope. The code runs through and I also get the correct "sessionId" from "Target.attachToTarget" but "self.location.href" returns the URL from the page rather than the worker.

Trying to get the worker instance with "page.workers()" always just returns an empty array.

Is there anything I'm missing or even a different approach to this?

from playwright.sync_api import sync_playwright CDP_URL = "http://localhost:9222" with sync_playwright() as p: browser = p.chromium.connect_over_cdp(CDP_URL) context = browser.contexts[0] page = context.pages[1] cdp = context.new_cdp_session(page) targets = cdp.send("Target.getTargets")["targetInfos"] for t in targets: t_targetId = t["targetId"] t_type = t["type"] t_url = t.get("url", "") t_title = t.get("title", "") if t_type == "worker": workerId = t["targetId"] attach = cdp.send( "Target.attachToTarget", { "targetId": workerId, "flatten": True } ) worker_session_id = attach["sessionId"] cdp.send( "Runtime.enable", {"sessionId": worker_session_id} ) result = cdp.send( "Runtime.evaluate", { "expression": "self.location.href", "sessionId": worker_session_id, "returnByValue": True } )
Read Entire Article