Sending a message from the popup to content or content-ui
saulable opened this issue · comments
I have this code in my Popup.tsx to handle a click
const handleClick = async () => { // Send a message to the background script to execute the content script const response = await chrome.runtime.sendMessage({greeting: "hello"}); };
Which gets received correctly to the background/index.ts file
chrome.runtime.onMessage.addListener( function (request, sender, sendResponse) { console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension"); if (request.greeting === "hello") { console.log("TABS", tabs) const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true }); const response = await chrome.tabs.sendMessage(tab.id, {greeting: "hello"}); } } );
However, I can't seem to get it to any response here. Inside of pages > content > lib > index.ts
chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension"); if (request.greeting === "hello") sendResponse({farewell: "goodbye"}); } );
I always get this error: Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.
I have check the content file being loaded and the function is in there.
Does anyone know how to receive messages via the content-ui or content folders from the popup?
Thank you for your contribution. We will check and reply to you as soon as possible.
Figured it out.
Put this in Popup.tsx
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { chrome.tabs.sendMessage(tabs[0].id, {action: "scrapePage"}, function(response) { console.log(response.article); }); });
Then in content-ui/src/index.tsx
chrome.runtime.onMessage.addListener((data, sender, sendResponse) => { if (data) { // Do something amazing } sendResponse({ article: "DONE" }); });