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...
        idx: strIndex,
        rst: strResult

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

function prse(message) {


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?

(Juraj Masiar) #2

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?

(Juraj Masiar) #4

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) {


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

(Martin Giger) #6

Are you looking in the correct consoles?


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