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

282
Vistas
Javascript send message from content.js to background.js

I read some of the chrome docs and got this basic example working.

Now I want to make the request based on an event happening. The event is triggered and contentUpdateData() runs, but the chrome.runtime.sendMessage within the function doesn't seem to work. Any ideas why?

/* content.js */ 
var data = []

chrome.runtime.onMessage.addListener(
    function(request, sesnder, sendResponse) {
        if (request.message === 'popupClicked') {
            contentUpdateData();
        }
    }
)

function contentUpdateData() {
    console.log('Code works up to here. Button clicked in popup.html, recieved in content.js. Need to get info from background.js')
    chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
        console.log(response.farewell);
        data = response.data
      });
}
/* background.js basic example from chrome */ 
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting === "hello")
      sendResponse({farewell: "goodbye", data: null});
  }
);
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You need to return true from the event listener in backgroundjs. This saves sendResponse() from garbage collection.

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.greeting === "hello") sendResponse({ farewell: "goodbye", data: null });
  // VERY IMPORTANT
  return true;
});
about 4 years ago · Juan Pablo Isaza Denunciar

0

Somehow the background.js did not sync properly after updating the extension. This was the cause for the error.

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