Sending a response from background.js not working in content script

  firefox-webextensions, javascript

I’m trying to send and receive a response in a firefox extenstion. I’m able to send the response successfully using the following code in my content script:

function notifyBackground(message) {
    var sending = browser.runtime.sendMessage({requestType: message});
    sending.then(handleResponse, handleError);
}

document.getElementById('downloads-select').addEventListener('click', function () {
    notifyBackground("requestDownloads");
});

When this is sent from the content script, in the browser console I can see the request successfully in the background script: Object { requestType: "requestDownloads" }. However when I try to reply with the following code in the background script:

function onError(error) {
    console.log(`Error: ${error}`);
}

function getFiles(sendResponse) {

    function handleError(error) {
        console.log(`Error: ${error}`);
    }

    function handleDownloads(downloads) {
        var results = "";
        for (var download of downloads) {
            results += `<p class="found-download-results">${download.filename}</p><br>`
        }
        sendResponse({response: results});
    }
    var searching = browser.downloads.search({
        limit: 25,
        orderBy: ["-startTime"],
    });
    searching.then(handleDownloads, handleError);
}

function handleResponse(request, sender, sendResponse) {
    console.log(request);
    var requestType = request["requestType"];
    if (requestType === "requestDownloads") {
        getFiles(sendResponse);
    }
}

From the content script I get that the response is undefined: background.js sent a response: undefined. I have the feeling there’s something simple that I’m missing, my manifest file looks like this:

...
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["app/scripts/hub.js"]
    }
  ],
  "content_security_policy": "script-src 'self'; object-src 'self'",
  "permissions": [
    "webNavigation",
    "webRequest",
    "webRequestBlocking",
    "cookies",
    "tabs",
    "http://*/*",
    "https://*/*",
    "ws://*/*",
    "wss://*/*",
    "storage",
    "downloads",
    "sessions",
    "file://*/*"
  ],
  "background": {
    "scripts": [
      "app/scripts/background.js"
    ],
    "page": "app/templates/background.html",
    "persistent": true
  },
...

What am I doing wrong to where the response is coming back as undefined?

Source: Ask Javascript Questions

LEAVE A COMMENT