🧩 Plasmo Developers�PD
🧩 Plasmo Developers3y ago
18 replies
AB7zz

How do I message from background to my content script?

background.tsx
chrome.webNavigation.onCompleted.addListener(async(details) => {
    if(details.frameType == "outermost_frame"){
        console.info("The user has loaded my favorite website!");
        console.log(details)
        const tabId = details.tabId
        chrome.tabs.sendMessage(tabId, {message: "Message from background script"}, function (response) {
            if (chrome.runtime.lastError) {
                console.error(chrome.runtime.lastError);
            } else {
                console.log('Message sent to content script:');
            }
        });
    }
}, filter);


content.tsx
const handleMessage = (message, sender, sendResponse) => {
    console.log('Message received in       content.jsx:', message);
    sendResponse({message: "Response from content.jsx"})
}
React.useEffect(() => {
    console.log('content is loaded')
    chrome.runtime.onMessage.addListener(handleMessage)
    return () => {
      chrome.runtime.onMessage.removeListener(handleMessage);
    };
  }, [])


I want to send the tab details from my background to the content script. Any help is really appreciated. I'm so tired of trying to do this.
Was this page helpful?