0

I am trying to send the result data in background.js to content script.

this is content script part:

...
chrome.runtime.sendMessage(keyword, function(response) {
    try{
        console.log("Response: "+ response[data]);
    }catch(e){
        console.log(e);
    }
});
...

this is background.js:

chrome.runtime.onMessage.addListener(function(request,sender,sendResponse){
     ...
     xhrGet(url, function(xhr){
         console.log(xhr.responseText);
         var obj = JSON.parse(xhr.responseText);

         var result = "";

         for(var i = 0 ; i < obj.mean.length ; i++){
             result+=obj.mean[i];
             if(i != (obj.mean.length-1)){
                 result+=", ";
             }
         }
         console.log(result); //***Here***
         sendResponse({data: result});
    });
    ...
});

function xhrGet(url, callback){
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.onreadystatechange=function(){
        if(this.readyState==4){
            callback(this)
        }
    };
    xhr.send()
}

This fetches data well after HTTP request. console.log(result) at the ***Here*** part prints the result that I want.

However, as far as I know, sendResponse() returns the result data to the content script as response variable which is the parameter of the callback function. However, it keeps printing undefined. So, I guess background.js has a problem when it sends the data because undefined means content script hasn't gotten any data yet.

What's the problem and How can I fix this?

c-an
  • 3,543
  • 5
  • 35
  • 82
  • 1
    Possible duplicate of [Chrome Extension Message passing: response not sent](https://stackoverflow.com/questions/20077487/chrome-extension-message-passing-response-not-sent) – wOxxOm Feb 04 '19 at 16:40
  • 1
    As shown in the linked thread you need to keep the channel open by returning true from the onMessage listener. – wOxxOm Feb 04 '19 at 16:40
  • @wOxxOm, I added `return true` in xhrGet(). And also tried placing `return true` after calling the method. However, both cases didn't work for me. – c-an Feb 04 '19 at 16:54
  • The only correct place is in the onMessage listener. Make sure you've reloaded the extension. Otherwise I can only guess you have another `return` or something else not shown in the question. – wOxxOm Feb 04 '19 at 16:58
  • 1
    Wait, your content script should access `response.data` not `response[data]`. Don't forget to reload both the extension and the web page after editing. – wOxxOm Feb 04 '19 at 17:00

0 Answers0