chimerical
chimerical

Reputation: 6013

How to grab data from webpage in Chrome and output into Chrome extension popup?

For a Google Chrome extension, none of the Javascript I write to manipulate the DOM of the extension popup.html seems to have any effect on the popup's DOM. I can manipulate the DOM of the current webpage in the browser just fine by using content_script.js, and I'm interested in grabbing data from the webpage and outputting it into the extension popup, like so (below: popup.html):

<div id="extensionpopupcontent">Links</div>
<a onclick="click()">Some Link</a>

<script type="text/javascript">
 function click() {
  chrome.tabs.executeScript(null, {file: "content_script.js"});
  document.getElementById("extensionpopupcontent").innerHTML = variableDefinedInContentScript;
  window.close();
 }
</script>

I tried using chrome.extension.sendRequest from the documentation at http://code.google.com/chrome/extensions/messaging.html, but I'm not sure how to properly use it in my case, specifically the greeting and the response.

contentscript.js
================
chrome.extension.sendRequest({greeting: "hello"}, function(response) {
  console.log(response.farewell);
});

Upvotes: 6

Views: 15641

Answers (1)

Mohamed Mansour
Mohamed Mansour

Reputation: 40169

So far, what you have done is correct. The only thing you are missing is that you need to setup a chrome.extension.onRequest event listener to handle the message coming back from the content script to the popup.

So doing something like this in the popup should work (extra):

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
  if (sender.tab && request.greeting == "hello")
    sendResponse({farewell: "goodbye"});
  else
    sendResponse({}); // snub them.
});

What the above snippet will do, it will listen for events from the content script (sender.tab == true when its coming from a content script).

If you read the entire page on messaging, it explains all this with nice examples: http://code.google.com/chrome/extensions/messaging.html

Upvotes: 4

Related Questions