Reply to chrome.runtime.sendMessage is `undefined`

Hello,

Some users of my add-on (GroupSpeedDial) are experiencing rare issue that I managed to identify as this:

From my content script I send message to my background script using this code:
chrome.runtime.sendMessage({type: 'getImages'}, data => { /* data parameter is undefined! */ })
My background script replies using code:
chrome.runtime.onMessage.addListener((data, sender, sendResponse) => { sendResponse({ /* some data in Object, never undefined */ }) })

Now my question is, how can I receive response with the undefined message, when such message cannot be even send?
What can be happening if I do get the response but it’s undefined?

I understand something is wrong. But unfortunately I’m unable to reproduce this error but I’m getting several e-mails every day reporting it. Also usually it disappears after reloading the page or restarting browser.

I even implemented a repeater function that will try to send this message 5 more times, each time with increased delay, each time waiting for response, but it didn’t helped.

I suspect this can be related with upgrade mechanism of extension or upgrade of Firefox as I tend to get more e-mails right after releasing a new version.

One scenario where this could happen is if there are multiple onMessage listeners.

Well this sounds interesting.
I have only single background script with single onMessage handler created during the initialization so there is no way it could be registered twice (but I do have a onMessageExternal handler in the same file for messages from my other add-on).

Anyway I can try to add validation using hasListener method before creating it.

Thank you for this info!

EDIT:
Using hasListener didn’t helped as I’m still getting same error reports from my new version.
I will try to remove the callback so instead of calling sendResponse I will be sending normal message using chrome.tabs.sendMessage(sender.tab.id, { /* data */ }), maybe it will help.

Anyway I think I should report it in bugzilla although I really hate reporting bugs I can’t reproduce :frowning:

After reporting the bug I learned that when using callback API, you need to check:
chrome.runtime.lastError
And in case of errors, the callback will be always called with undefined pramater value.
I guess it’s time to migrate to Promises now as this is just pure evil.

Regarding possible errors, it could be for example:
“Could not establish connection. Receiving end does not exist.”
(who knows why)

1 Like