Skip to content Skip to sidebar Skip to footer

Passing Message From One Listener To Another

I'm developing an extension for Chrome, and here's the workflow I'm trying to achieve: popup sends message -> content script 1 listens -> content script 1 sends message ->

Solution 1:

There are 2 sendMessage functions in Chrome API.

So the call to chrome.runtime.sendMessage() in your first content script can't reach any other content script.

What's more, you can't call chrome.tabs directly from a content script.

To do what you want, you need to set up a background script that will act like a proxy between CS1 and CS2. Technically, you could use the popup, but it's unreliable, as the popup may be closed and then nobody would be listening. The background page (or better yet, an event page) is designed specifically for that purpose.

So the scheme becomes: popup -(tabs.sendMessage)-> CS1 -(runtime.sendMessage)-> background -(tabs.sendMessage)-> CS2

Do note that background page will need to know the tab ID to send the message to. If it's the same tab for some reason, e.g. you're trying to message across frames, you can use the sender parameter in the callback.

See Messaging docs for more details.

Post a Comment for "Passing Message From One Listener To Another"