Reputation: 11
I connect content.js with background.js to do 2 different tasks: inject local HTML and fetch data from another webpage.
Currently, the createContainer()
starts after fetchweb()
is done and I am not sure why (I need createContainer()
to run first). I tried to transform both functions into Promise but still the same result
Content.js
function createContainer1() {
// call html file container
chrome.runtime.sendMessage({ cmd: "read_cont1" }, function (html) {
$("#container1").html(html);
});
// more code
}
function fetchWeb() {
chrome.runtime.sendMessage(
{ cmd: "send_url", url: window.location.href},
function (response) {
console.log(JSON.stringify(response));
}
);
}
createContainer1()
fetchWeb()
background.js
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.cmd == "read_cont1") {
$.ajax({
url: chrome.extension.getURL("container1.html"),
dataType: "html",
success: sendResponse,
});
return true;
} else if (request.cmd == "send_url") {
sendResponse({ review_url: fetchData(request.url) });
return true;
}
});
Upvotes: 1
Views: 843
Reputation: 172
Your two sendMessages are both asynchronous functions and--unless specifically dealing with asynchronous coding through callbacks, promises, or async/await--I don't think there's any other way to guarantee which resolves first.
If fetchWeb should run every time after createContainer sends its message, you could add fetchWeb to sendMessage's callback (and then remove it from your main body):
...chrome.runtime.sendMessage({ cmd: "read_cont1" }, function (html) {
$("#container1").html(html);
fetchWeb();
});...
If fetchWeb should only sometimes run, you could pass data into the createContainer function answering that question:
function createContainer1(executeFetchWeb) {
// call html file container
chrome.runtime.sendMessage({ cmd: "read_cont1" }, function (html) {
$("#container1").html(html);
if (executeFetchWeb) {fetchWeb()}
});
// more code
}
If there's something else happening in "//more code" that needs to happen before fetchWeb runs, it would be helpful to see that. But unless that code is asynchronous as well, I imagine that code is already executing first. This could all be done with promises as well, but sendMessage is already setup to work well with callbacks. From the documentation:
chrome.runtime.sendMessage(
extensionId?: string,
message: any,
options?: object,
responseCallback?: function,
)
Upvotes: 1