Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

275
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda