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…
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:
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?
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.