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?