How to send message from background to content script that inside in offscreen and iframe?

I have the next chain: background > offscreen > iframe > inner content script. For this target in manifest set all_frames to true. How to send message from background to inner content script?

The chrome.tabs.queue don’t return such tab id in order to use chrome.tabs.sendMessage. Other chrome.runtime.sendMessage only for offscreen.

Sending Messages through multiple Layers in Chrome Extension

Sending messages through multiple layers in Chrome Extensions, such as from a background script through an offscreen tab to a content script inside an iframe, can be done using the chrome.runtime.sendMessage and chrome.runtime.onMessage APIs.

My approach:

1. Background Script
Make use of the chrome.runtime.sendMessage API to send a message over to the content script of the offscreen tab’s.

The Script:

chrome.runtime.sendMessage({ target: "offscreen", data: "yourMessageData" });

2. Offscreen Content Script
Listen for the message that came from the background script. When the message arrives, forward it to the content script inside the iframe.

The Script:

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.target === "offscreen") {
        // TODO: Send the message to the iframe content script
        let iframeWindow = document.querySelector('iframe').contentWindow;
        iframeWindow.postMessage({ target: "iframeContent", data: message.data }, '*');
    }
});

3. iframe Content Script
Listen for the message from the offscreen content script using the window’s message event.

The Script:

window.addEventListener("message", (event) => {
    if (event.data.target === "iframeContent") {
        // TODO: Handle your message data here
        console.log(event.data.data);
    }
});

Side Notes:

  • Safety tip: Always check where messages come from when using postMessage. While we used ‘*’ for simplicity, specify the sender’s origin for security.

  • Target messages wisely: Use the ‘target’ property to ensure only the right recipient processes the message. Adjust it to suit your needs.

  • Cross-origin iframes might limit DOM access. Make sure both sides agree on message format for smooth postMessage handling.
    If you have any questions feel free to add a comment.

Leave a Comment