Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

274
Visualizações
Multiple function call to chrome.runtime.sendMessage() with synchronous behaviour

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;    
    }
});
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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,
)
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda