Belows are my code snipets.
How to sendResponse in place A or B or C?
It seems like sendResponse only work in place D and not in A or B or C because ABC are after async await methods.
// in background.js, add listeners
chrome.runtime.onMessage.addListener(
async function (request, sender, sendResponse) {
if (request.type === 'get-text') {
// sendResponse({abc:'abc'}) // works here. D
const tab = await getTab();
// sendResponse({bcd:'bcd'}) // doesn't work here. C
const data = await chrome.scripting.executeScript({
target: { tabId: tab.id },
function: () => {
// get text from dom
return text;
},
args: []
}, (bundleData) => {
// sendResponse({test:'test'}) // doesn't work here. B
});
// sendResponse({efg:'efg'}) // doesn't work here. A
}
}
// in popup.jsx
useEffect(() => {
const getText = async () => {
const response = await chrome.runtime.sendMessage({ type:'get-text' })
console.log(response);
}
getText().catch(e=>console.log('error: ', e))
}, [])
My chrome extension is build on React 18. Using manifest v3