Short version: the first time I send a message from a script injected inside a web page to a service worker using
chrome.
runtime.sendMessage, I *always* get a response inside the callback function that is
undefined, even if according to Chromium the service worker is active. Subsequent attempts seem to work correctly. If the method that I invoke to generate the data to be put inside the message fails, I still send a message containing an object, but in this cast the object contains an error. So the problem isn't that method failing.
More detailed version: I'm developing an extension to encrypt and decrypt Gmail's emails. For this, I let the user compose the email as usual, and then there's an added button in the compose view that encrypts and sends the email (for interacting with Gmail's UI, I'm using the Gmail.js library. This is why the script that send the message to the service worker is injected into Gmail's web page. So form Chromium's perspective is the web page that sends the message). The first time that I click on that button, I get the following two errors in the console:
Error handling response: TypeError: Cannot read properties of undefined (reading 'ciphertext')
Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.
This happens even if according to Chromium the service worker is active (and indeed I can inspect the service worker's output prior to this to confirm it) and even if the service worker is supposed to send an object containing an error if the encryption fails. Subsequent attempts work.
As a workaround, I could check if the response is undefined and send the message again, but I would like to find the root cause of the issue, any ideas about what's wrong here?
Thank you for your help,
Giacomo