'Chrome extension – async onMessage response
I'm having an issue with chrome handling. Here is how I handle communication between my content script, and my background service worker.
Content script
const sendMessage = (msg) => {
return new Promise((resolve) => {
console.log('1');
chrome.runtime.sendMessage(msg, (data) => {
console.log('4');
resolve(data);
});
});
};
sendMessage.then(...)
Background listener
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
console.log('2');
myAsyncHandler().then((data) => {
console.log('3');
sendResponse(data);
});
return true;
});
I have this whole thing running in a new tab, and now:
- When I open my first new tab, everything works as expected – 0 issues – log statements in order: 1, 2, 3, 4
- When I open my second tab (2 tabs now running), the issue appears as the
sendMessagereturnsnull. Log statements appear in order 1, 2, 4, 3.
I've tried to debug this, but no luck at all. I've even tried to log chrome.runtime.lastError when I received null in the sendMessage callback – but that's undefined.
I'd be grateful for all hints on what might be causing it!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
