August
August

Reputation: 12558

Messaging between content script and popup script in Chrome extension

I'm trying to create a popup chrome extension that shows information about the DOM in the current page, which seems to require messaging. I've been able to send messages to the background, but I need the data to be specific to the current page, as the background is identical to all popups/pages.

In popup.js, I send a message when the DOM is loaded (should trigger when popup is clicked?)

document.addEventListener('DOMContentLoaded', function() {
    chrome.runtime.sendMessage({method: "getTableData"}, function response() {
    });
});

I also have a listener in the contentscript.js (and background.js for testing)

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if(request.method == "getTableData") {
    console.log("table request found!");
  }
});

Then, when I activate the popup, the background console outputs table request found!, while the console for the current page doesn't.

Thanks.

Upvotes: 2

Views: 816

Answers (1)

rsanchez
rsanchez

Reputation: 14657

You need to use chrome.tabs.sendMessage instead of chrome.runtime.sendMessage to send a message to a content script.

Upvotes: 2

Related Questions