1

I'm trying to send a message from my service worker to my content script which contains the headers of certain request using chrome.webRequest.onBeforeSendHeaders. I can see the request being made in the network tab, but when I try to log the message to the console in my content script it doesn't show up.

manifest.json:

{
  ...,
  "content_scripts": [
    {
      "matches": ["https://example.com/*"],
      "js": ["content.js"]
    }
  ],
  "background": {
    "service_worker": "background.js"
  },
  "permissions": [
    "tabs",
    "webNavigation",
    "webRequest"
  ]
}

background.js:

async function getCurrentTab() {
  let [tab] = await chrome.tabs.query({active: true, lastFocusedWindow: true});
  return tab;
}

chrome.webRequest.onBeforeSendHeaders.addListener(
  async (details) => {
    let tab = await getCurrentTab();
    chrome.tabs.sendMessage(tab.id, 
      {message: "request_headers", payload: details.requestHeaders}
    );
  },
  {urls: ["https://api.example.com/resource.json"]},
  ['requestHeaders']
);

content script:

chrome.runtime.onMessage.addListener(
  (request, sender, sendResponse) => {
    if (request.message === "request_headers") {
      console.log(request.payload);
    }
  }
);
Jason
  • 47
  • 1
  • 7
  • Open [devtools for background.js](/a/10258029) and see if there are errors. You can also set breakpoints inside the listener and debug it. One common problem is reloading the extension without reloading the tab(s) or [reinjecting the content script(s)](/q/10994324). Another one is the lack of `"run_at": "document_start"` in the content script's declaration. BTW you should probably send to details.tabId not to the active tab. – wOxxOm Feb 21 '23 at 21:05
  • The devtools for background.js is empty, even after reloading the extension and the tab. I even tried only console logging something inside the callback function of the background script but still nothing show up which tells me it's not getting called at all. – Jason Feb 21 '23 at 21:19
  • If you set a breakpoint and it didn't trigger it means the listener is not called, which can happen if your `host_permissions` in manifest.json doesn't include the URL you observe. – wOxxOm Feb 21 '23 at 21:22

0 Answers0