Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

280
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!