background/servicework sendMessage() to sidepanel's iframe

1,214 views
Skip to first unread message

blue beard

unread,
Mar 4, 2024, 5:47:08 AM3/4/24
to Chromium Extensions
Hi there,

I started using sidepanel feature and I have an iframe under the sidepanel html.

How can I sendMessage() from background serviceworker directly to this sidepanel iframe?

I can sendMessage() to sidepanel via chrome.runtime.sendMessage().

I can sendMessage() to content script page's iframe via chrome.tabs.sendMessage().

but it seems it doesn't work for sidepanel's iframe since sidepanel is not under a tab and its iframe onMessage() doesn't respond to regular chrome.runtime.sendMessage() as well.

If anyone can provide some insights?

Thanks!

wOxxOm

unread,
Mar 4, 2024, 6:48:13 AM3/4/24
to Chromium Extensions, blue beard
Assuming the iframe is a web page, your content script that runs inside should initiate port-based messaging via chrome.runtime.connect. The background script can send the data back by using port.postMessage inside its chrome.runtime.onConnect listener. If necessary, you can also store the port in a global variable to be used in other listeners while the background script is alive.

There's also an elaborate solution for binary data (e.g. typed arrays, blobs, array buffer): the content script transfers a MessageChannel port via parent.postMessage, the side panel transfers it further via navigator.serviceWorker messaging to the background script's self.onmessage listener. Note that to avoid abuse from the web page you might want to use a random id as the message body, which you can store in chrome.storage.session or send explicitly from the content script to the side panel via chrome.runtime.sendMessage.
Reply all
Reply to author
Forward
0 new messages