rrcustom
rrcustom

Reputation: 65

Google Chrome Extension - content_scripts to communicate with background_page js files

In my Google Chrome extension, I have a content_script that I want to communicate with my background_page. Does anyone know how this can be done?

I have found a couple tutorials going over how a background page can communicate with a content_script but, as I have stated, I need the opposite to occur.

I want to run an automated script to clear my cache every 24 hours. I cannot do this from a content_script, I have to do this from the background page. The only way I can get this to work right now is if I tie in a "button" but as I said before, I want it automated to run every 24 hours.

BTW- I am already aware that Content Scripts cannot: Use chrome.* APIs (except for parts of chrome.extension) Use variables or functions defined by their extension's pages Use variables or functions defined by web pages or by other content scripts

As you can see the first item listed there is: chrome APIs, but I need to use a chrome API in my content_script, so hopefully someone has a work around. Please let me know.

Upvotes: 1

Views: 1250

Answers (1)

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94319

Message Passing Doc from Google

Content script:

chrome.extension.sendRequest({greeting: "hello"}, function(response) { //request
  console.log(response.farewell);           //receive response
});

Background page:

chrome.extension.onRequest.addListener(     //listen to requests
  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"});  //send response
  });

Also you can open up a Long-lived connection between content scripts and background page:
http://code.google.com/chrome/extensions/messaging.html#connect

contentscript.js
================
var port = chrome.extension.connect({name: "knockknock"});
port.postMessage({joke: "Knock knock"});
port.onMessage.addListener(function(msg) {
      if (msg.question == "Who's there?")
    port.postMessage({answer: "Madame"});
  else if (msg.question == "Madame who?")
    port.postMessage({answer: "Madame... Bovary"});
});


background.html
===============
chrome.extension.onConnect.addListener(function(port) {
  console.assert(port.name == "knockknock");
  port.onMessage.addListener(function(msg) {
    if (msg.joke == "Knock knock")
      port.postMessage({question: "Who's there?"});
    else if (msg.answer == "Madame")
      port.postMessage({question: "Madame who?"});
    else if (msg.answer == "Madame... Bovary")
      port.postMessage({question: "I don't get it."});
  });
});

Upvotes: 3

Related Questions