Remove register-sw.js and its usage.
Extensions register their background service worker automatically when you declare it using "background" key in manifest.json
Rework your code to get the response directly via messaging:
const addTitleToWatchlist = () => {
return new Promise(resolve => {
chrome.runtime.sendMessage({ type: "ADD_TO_WATCHLIST" }, resolve);
});
};
Remove async from onMessage listener declaration. Extensions in Chrome can't return a Promise yet and it's unclear if Chromium team will implement it properly or they will keep the old nonsensical method explained below.
- To do something asynchronously in onMessage you should use a separate Promise (or function) and return true from the listener. The listener itself can't be async because this keyword makes the function return a Promise.
- Use sendResponse as shown in the documentation instead of using storage.
- Remove chrome.tabs.query and use sender parameter of the listener because the tab that sent the message may be inactive.
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "ADD_TO_WATCHLIST") {
addToWatchList(message, sender).then(sendResponse);
return true; // this will keep the internal messaging port open
}
});
async function addToWatchList(message, sender) {
const articleId = getArticleId(sender.url);
const requestedArticle = await getArticleInfos(articleId);
return prepareMessage(requestedArticle, articleId);
}