Skip to content

Inspect subtargets like a service worker

Paul Irish edited this page Oct 13, 2017 · 1 revision

Two key things:

  1. Targets form hierarchies in remote debugging. The Target domain allows traversing targets and sending messages to sub-targets.
  2. SW does not run JS in itself, it has a dedicated worker in it that runs JS, that dedicated worker is exposed as its sub-target.

Once connected to the page, issue Target.setAutoAttach({autoAttach:true}). That would emit Target.attachedToTarget with the dedicated worker targetId / sessionId. After that use Target.sendMessageToTarget to send messages to that sub-target over your SW connection. The protocol for speaking with the sub-targets is the same remote debugging protocol. So in order to send Runtime.evaluate to a sub-target, you would need to do:

client.send("Target.sendMessageToTarget", { 
  sessionId: <id>, message: "{id:<sequence_num>, method:'Runtime.evaluate', args : {expression: 'foo'}}"
});

But in this case, you'll be sending sending this from the Page ==> Service Worker ==> Dedicated Worker, so you'll need to wrap it a second time:

client.send("Target.sendMessageToTarget", {
  sessionId:"0d389d97-b8bb-42b0-8a61-75ab9ba9e717:1",
    message: `{
      "id":2,
      "method":"Target.sendMessageToTarget",
      "params":{
        "sessionId":"dedicated:49960.2-1",
        "message":"{
          \"id\":1,
          \"method\":\"Runtime.evaluate\",
          \"params\":{\"expression\":\"foo\"}}"
    }
  }`
});