Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams 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.

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;