I have read the plethora of forums and reddit links and stackoverflow QnA and non answers the question or explains it in a clear manner. I've been at this for 2-3 days now just on this async await promises bs.
I have an async popup function that calls a chrome.tabs.sendMessage as you can see below, it is very, very basic. I send a message, wait for a response. Viola, done.
My understanding of a callback function tells me that chrome.tabs.sendMessage WILL wait for a response THEN run the function, but what happens is the function runs anyway? and I can't make sense of it. It just runs it receives asap without waiting for the content script to finish. What's the point of a callback function then?
I've tried adding await before sending and await on the callback function and any which way possible but it does NOT work. I don't understand it. Program just runs without waiting.
I've read this doesn't work. and this makes no sense. Promises wait on a "complete" message and somehow that makes it wait. But tabs.message callback function also WAITS on a response but still runs anyway and doesn't wait on anything?
document.addEventListener('DOMContentLoaded', async function() {
console.log('got tabs id');
tab = await getCurrentTab();
console.log('Active tab ' + tab.id);
console.log('Sending Message to Content');
chrome.tabs.sendMessage(tab.id, {action: "getDOM"},function (ret) {
console.log('Receiving Message from Content');
try {
if (!ret.incident.length) return;
globalThis.response = ret;
processResponse(response);
}
catch(err) {
console.log('doing nothing, bad return data')
window.close;
return;
}
});
return;
});
OP is obviously very confused.
callback, async/await, promises are the same thing just written differently. Below is the updated code using promises only, and callbacks when absolutely necessary. In this case, chrome's tabs.sendMessage does not return a promise like they do in Firefox. So it must use the callback form. The content_script in this case does a timeout with sendResponse and it works OK.
document.addEventListener('DOMContentLoaded', function() {
console.log('got tabs id');
let queryOptions = {active: true, currentWindow: true};
chrome.tabs.query(queryOptions)
.then((tabs) => {
chrome.tabs.sendMessage(tabs[0].id, {action: "getDOM"}, (response) => {
console.log(response);
// processResponse(response);
});
})
.catch((err) => {
console.log(err);
window.close();
return;
});
});