Sending message from background script to content script

I am sending a message like so from the background-script.js:

   browser.tabs.executeScript(itid, {
      file: "content-script.js"
  }).then(() => {
      //  The below should run concurrently as the update script will be waiting for it...
    browser.tabs.sendMessage(
      itid,
      {
        idx: strIndex,
        rst: strResult
      }
    ).catch(onError)
  });

And receiving it like so in content-script.js:

function prse(message) {
	console.log(message);
}

console.log("here");
browser.runtime.onMessage.addListener(prse);

However when I do so, content-script.js launches (ā€œhereā€ is logged) but the message isnā€™t caught, instead it jumps back to the background-script and fires an undefined errorā€¦

Anyone know what Iā€™m doing wrong here?

Of course you need to wait for the execution of the content script to be finished. Itā€™s asynchronous so there is no guarantee that the content script has finished registering the message listener before you sent it a message.

But the second example looks fine, is it still not working?
Also to make your code more readable, you may want to use await instead of then. Like this:

await browser.tabs.executeScript(itid, {file: "update.js"});
await browser.tabs.sendMessage(...)

Thanks for your response, I adjusted to use the second example again.
The console is now logging ā€œmessageā€ so the message is being received but console.log(message) is still coming up as unavailable, Iā€™m hardly calling this wrong in my example am I?

What do you mean by that? There should be two logs in the console, first the ā€œhereā€ and then the object you send there.

Oh apologies I made an edit to content-script.js to ensure the message callback was triggered:

function prse(message) {
	console.log("message");
	console.log(message);
}

browser.runtime.onMessage.addListener(prse);

So the first console log works (a message is being received), but the second (the actual object) is unavailable.

Are you looking in the correct consoles? https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Debugging

And just like that, it works :joy:

I feel like a prize idiot, I was thrown off as the ā€œmessageā€ was still appearing in the (popup) browser console. The expected content script output is now showing for the tab in the web console for that page.

Thanks @freaktechnik and @juraj.masiar for your help

2 Likes