1

Content script

chrome.runtime.sendMessage({
    method: "getComments"
}, function(response) {
    var comments = response.arr;  //response is undefined
    ...
});

background page

chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.method === "getComments")
  chrome.tabs.query({
    'active': true,
    'lastFocusedWindow': true
  }, function(tabs) {
    var serverUrl = newServerUrl + '?domain=' + tabs[0].url;
    var xhr = new XMLHttpRequest();
    xhr.open("GET", serverUrl);
    xhr.setRequestHeader("Content-type", "application/json");
    xhr.onload = ()=> {
      sendResponse({arr: 'something'});  //it seems this is not working
    };
    xhr.send();
  });

I'm trying to get the address of current tab using background page, send the address to a server to retrieve data, and pass the retrieved data back to content script. But sendResponse doesn't return anything to the content script. I'm developing a chrome extension.

Abel Zhu
  • 27
  • 2
  • 7

1 Answers1

5

Having read the documentation

This function becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until sendResponse is called).

So, in the case of getComments you need to return true, as follows

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method === "getComments") {
        chrome.tabs.query({
            'active': true,
            'lastFocusedWindow': true
        }, function(tabs) {
            var serverUrl = newServerUrl + '?domain=' + tabs[0].url;
            var xhr = new XMLHttpRequest();
            xhr.open("GET", serverUrl);
            xhr.setRequestHeader("Content-type", "application/json");
            xhr.onload = () => {
                sendResponse({
                    arr: 'something'
                }); //it seems this is not working
            };
            xhr.send();
        });
        return true;
    }
});
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87