views:

162

answers:

1

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);
});
+1  A: 

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

Mohamed Mansour
Turns out that I also needed this in the content script:var myMessage = "..."; // Variable to pass to the extension chrome.extension.sendRequest({greeting: myMessage}, function(response) {});And where you have sendResponse({farewell: "goodbye"}); in popup.html, that is where we do something with that variable.
chimerical

related questions