How can I guarantee that tabs.sendMessage can be received?

I’m banging my head against this one.

I’m using https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/sendMessage from a background script to a content script.

What I want to achieve is to guarantee that a message can be sent from background and received in content as soon as a tab is ready to receive it, with no human interaction.

I need this functionality because I modify the contents of a page, based on the collected IP address of the currently loading tab, and as far as I can understand I can only determine the IP from a background script.

The approach I’m currently:

  • Listen for webrequest.onCompleted for the current tab, and extract the ip from “main_frame”
  • Listen for webNavigation.onCompleted

For each event in either of these I make an attempt to send a message from background to content using tabs.sendMessage, in the assumption that the receiver in the tab is ready.

This has proven to be a flawed way of doing this, so I need some hints/guiding into what I can do instead. When I load a new tab and enter a URL, it fails to receive a message 95% of the times.

How does one make sure that the receiving end is ready? Is there an event/method/way that can guarantee I am able to send a message that will be received, without the user having to click e.g. a button?

The most reliable way would be to immediately send a message from the content script to the background script and then reply with the actual data.

1 Like

Huh, it’s so obvious now that you mention it.

I just did a modification to the code and it seems so much more solid. Thanks for that!

While I have you on the line; do you know if I can assume that webRequest.onComplete has executed before the content script can send a message to background?
The reason I’m asking is that I’d rather not add unnecessary “retry”-code to this if it’s not relevant/applicable.

I don’t think there’s any order guarantee, since you’re in JS and your background page’s event loop could be doing anything in relation to the content script etc.