I am trying to request some data from one script to another. The script that has the data has this listener with my guess at returning that data:
chrome.runtime.onMessage.addListener(function(message,sender) {
if (message.msg=="start") {
start();
}
else if (message.msg=="stop") {
stop();
}
else if (message.msg=="sendData") {
sendResponse(data);
else {
configure();
}
});
What I don't understand is how to recover that data in the requesting script. Do I need a listener in the requesting script or is the data returned as part of the request thus?
data=await chrome.runtime.sendMessage({msg:"sendData"});
TIA.
Using Joe's suggestion, modified for async operation, here is my code:
In the requesting background script:
chrome.runtime.sendMessage({msg:"sendData"},await function(response) {
console.log(response.data);
});
In the request processing script:
chrome.runtime.onMessage.addListener(async function(message,sender,sendResponse) {
if (message.msg=="start") {
start();
}
else if (message.msg=="stop") {
stop();
}
else if (message.msg=="sendData") {
var data_obj=await requests(base_url+"/projects.json");
console.log(data_obj);
sendResponse({"data":data_obj.results});
}
else {
configure();
}
});
The sendResponse seems to wait for the requests call to return. However, the response function does not wait. So the problem now is how to get the response function to wait until the requester sends the data.
Updated again per Joe's suggestion. This is how I interpreted your code. Requesting script:
chrome.runtime.sendMessage({msg:"sendData"},function(response) {
const data=response.data;
console.log(data);
});
Processing script
chrome.runtime.onMessage.addListener(async function(message,sender,sendResponse) {
if (message.msg=="start") {
start();
}
else if (message.msg=="stop") {
stop();
}
else if (message.msg=="sendData") {
requests(base_url+"/projects.json").then(data=>data.json()).then(result => {
sendResponse({"data":result});
});
return(true);
}
else {
configure();
}
});
Unfortunately I get this error on "const data=response.data":
Error handling response: TypeError: Cannot read properties of undefined (reading 'data') at chrome-extension://fplbgdfknpplbjbggkkhnpnifgfeojpo/config_mgmt.js:87:24