Search code examples
javascriptgoogle-chrome-extension

onMessage.addListener : sendResponse


Forgive me if ever an answer has already been given, I've been searching for more than 1 hour but didn't find a way to fix my problem.

So here is my problem :

I am coding a chrome extension and have 2 JS scripts, "script.js" and "background.js". In my script.js, I am using chrome.runtime.sendMessage to message my background script.

Withing my background script, I made a listener to receive the message and download several images from links provided via the message, Which means the function may take up to 1 minute before the download to be finished. (By the way, I am using promise, then I know my code is executed step by step)

script.js

chrome.runtime.sendMessage({message: "download", parameters: images}, function (response) {
    console.log(response);
});

background.js

chrome.runtime.onMessage.addListener(function (arg, sender, sendResponse) {
    doSomeLongStuff().then(function () {
        sendResponse(myResponse);
        return true;
    })
});

And in my script, I am unable to receive my answer. Even if I add a setInterval to the responseCallback, the response will always be undefined

If ever someone could tell me if there is a way to tell the responseCallback to wait for a long answer, any help would be appreciated.


Solution

  • This is a common problem, i.e. returning a response from an asynchronous operation. Chrome will ignore any call to sendResponse() if it's not done synchronously.

    The solution is not to think in terms of sending a response, but sending a subsequent message in its own right.

    chrome.runtime.onMessage.addListener(function (arg, sender, sendResponse) {
        doSomeLongStuff().then(function () {
            //don't call sendResponse() here, send a separate message to script.js
            return true;
        })
    });
    

    You send this via chrome.tabs.sendMessage in the callback to a request to chrome.tabs.query. Docs.