My extension is based on manifest V2, and is cross-browser compatible basing on browser-polyfill. I need to migrate to manifest V3. There are many communications between context and background using sendMessage in the extension. As written in many places, including official chrome documentation, in V3 sendMessage returns promises natively, so I removed polyfill and try to load extension, but it fails to work.
It appears that sendMessage do returns promise, but when logging to console, message from .then appears before message from message listener in service worker (former background), so the result is always undefined. What I’m doing wrong?
context.js:
if (typeof globalThis.browser === "undefined")
environment = chrome.runtime
else
environment = browser.runtime
onCompletePageLoad()
function onCompletePageLoad() {
let nmarr = [{request: "AA"}];
let snd = environment.sendMessage(nmarr);
console.log("SENDER = ", snd);
snd.then(
result => {console.log("AFTER MESSAGE RETURN = ", result) },
error => {}
);
}
background.js:
let environment
if (typeof globalThis.browser === "undefined")
environment = chrome.runtime
else
environment = browser.runtime
environment.onMessage.addListener(onContentMessage);
function onContentMessage(msg, sender, handleResponse)
{
console.log("MESSAGE RECEIVED");
return new Promise(resolve => {
setTimeout(() => {
console.log("TIMES OUT");
resolve("async response from background script");
}, 2000);
});
}
Result is:
SENDER = Promise {<pending>}
AFTER MESSAGE RETURN = undefined
(In the original extension logs from background.js appears on the same console as from context.js, but after I extract this piece to test extension background messages appears only on service-worker console, so I can't demonstrate the order of console messages)
manifest.json:
{
"manifest_version": 3,
"name": "messagetest manifest 3",
"version": "1.0",
"description": "Testing content to background message sending",
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
]
}