0

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});
  }
);
Bart
  • 442
  • 1
  • 3
  • 9

2 Answers2

1

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;
});
Spankied
  • 1,626
  • 13
  • 21
0

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

Bart
  • 442
  • 1
  • 3
  • 9