views:

269

answers:

1

Hi!:) In my extension, when a button named "mybutton1" in the popup.html is clicked, it sends a message "getvar1" to the contentscript.js, then the contentscript.js sends a message "i want var1" to the background.html to get an object named "var1".If the button named "mybutton2" is clicked, the contentscript.js gets the "var2" object. How should i do under this condition? What's more, i am a little confused about the chrome.extension.onRequest.addListener method and chrome.extension.sendRequest method.Could someone tell me the mechanism of the two methods? Thanks!

+2  A: 

Hi, onRequest.addListener and sendRequest is part of Chrome's extension Messaging. Which is located here http://code.google.com/chrome/extensions/messaging.html

Basically, you listen for a request using "onRequest.addListener" that someone sent from triggering a "sendRequest".

In your case, you put a "onRequest.addListener" in your content script to listen for requests coming from the Popup (using sendRequest). And from your content script, you can return a response back to your popup to handle what is happening. In your popup, you have direct access to the background page using chrome.extension.getBackgroundPage().

If you want your content script to communicate to your background page as well (which is not needed since your making stuff more complicated), you can add a "onRequest.addListener" to your background page which only listens for requests coming from the content script. To do that, Message Passing explains it perfectly. "sender.tab" if true, is a content script.

The example below (untested) shows what I mean about message passing. Remember, try to keep stuff simple, not complex.

Example

Popup.html

chrome.tabs.getSelected(null, function(tab) {
  chrome.tabs.sendRequest(tab.id, {method: "fromPopup", tabid: tab.id}, function(response) {
    console.log(response.data);
  });
});

ContentScript.js

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
  if (request.method == "fromPopup") {
    // Send JSON data back to Popup.
    sendResponse({data: "from Content Script to Popup"});

    // Send JSON data to background page.
    chrome.extension.sendRequest({method: "fromContentScript"}, function(response) {
      console.log(response.data);
    });
  } else {
    sendResponse({}); // snub them.
  }
});

BackgroundPage.html

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
  // From content script.
  if (sender.tab) {
    if (request.method == "fromContentScript")
      sendResponse({data: "Response from Background Page"});
    else
      sendResponse({}); // snub them.
  }
});
Mohamed Mansour

related questions