Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get data from a background page to the content script in google chrome extensions

I've been trying to send data from my background page to a content script in my chrome extension. i can't seem to get it to work. I've read a few posts online but they're not really clear and seem quite high level. I've got managed to get the oauth working using the Oauth contacts example on the Chrome samples. The authentication works, i can get the data and display it in an html page by opening a new tab.

I want to send this data to a content script.

i'm having a lot of trouble with this and would really appreciate if someone could outline the explicit steps you need to follow to send data from a bg page to a content script or even better some code. Any takers?

the code for my background page is below (i've excluded the oauth paramaeters and other )

` function onContacts(text, xhr) {
    contacts = [];
    var data = JSON.parse(text);
    var realdata = data.contacts;
    for (var i = 0, person; person = realdata.person[i]; i++) {
      var contact = {
        'name' : person['name'],
        'emails' : person['email']
      };


      contacts.push(contact); //this array "contacts" is read by the 
 contacts.html page when opened in a new tab

    }

    chrome.tabs.create({ 'url' : 'contacts.html'}); sending data to new tab
    //chrome.tabs.executeScript(null,{file: "contentscript.js"});
    may be this may work?

  };

  function getContacts() {
    oauth.authorize(function() {
      console.log("on authorize");
      setIcon();
      var url = "http://mydataurl/";
      oauth.sendSignedRequest(url, onContacts);

    });
  };

  chrome.browserAction.onClicked.addListener(getContacts);`

As i'm not quite sure how to get the data into the content script i wont bother posting the multiple versions of my failed content scripts. if I could just get a sample on how to request the "contacts" array from my content script, and how to send the data from the bg page, that would be great!

like image 248
rupertnorth Avatar asked Jan 15 '11 15:01

rupertnorth


People also ask

What does the background script do in Chrome extension?

Popup Script - Local JavaScript file for the extension DOM. Background Script - Provides persistence and handles background events. Content Script - Scripts that run in isolation in the context of the web page. Injected Script - Scripts that are programmatically injected into the web page.


2 Answers

You have two options getting the data into the content script:

  1. Using Tab API: http://code.google.com/chrome/extensions/tabs.html#method-executeScript
  2. Using Messaging: http://code.google.com/chrome/extensions/messaging.html

Using Tab API

I usually use this approach when my extension will just be used once in a while, for example, setting the image as my desktop wallpaper. People don't set a wallpaper every second, or every minute. They usually do it once a week or even day. So I just inject a content script to that page. It is pretty easy to do so, you can either do it by file or code as explained in the documentation:

chrome.tabs.executeScript(tab.id, {file: 'inject_this.js'}, function() {
  console.log('Successfully injected script into the page');
});

Using Messaging

If you are constantly need information from your websites, it would be better to use messaging. There are two types of messaging, Long-lived and Single-requests. Your content script (that you define in the manifest) can listen for extension requests:

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
  if (request.method == 'ping')
    sendResponse({ data: 'pong' });
  else 
    sendResponse({});
});

And your background page could send a message to that content script through messaging. As shown below, it will get the currently selected tab and send a request to that page.

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

Depends on your extension which method to use. I have used both. For an extension that will be used like every second, every time, I use Messaging (Long-Lived). For an extension that will not be used every time, then you don't need the content script in every single page, you can just use the Tab API executeScript because it will just inject a content script whenever you need to.

Hope that helps! Do a search on Stackoverflow, there are many answers to content scripts and background pages.

like image 68
Mohamed Mansour Avatar answered Sep 20 '22 11:09

Mohamed Mansour


To follow on Mohamed's point.

If you want to pass data from the background script to the content script at initialisation, you can generate another simple script that contains only JSON and execute it beforehand.

Is that what you are looking for?

Otherwise, you will need to use the message passing interface

In the background page:

// Subscribe to onVisited event, so that injectSite() is called once at every pageload.
chrome.history.onVisited.addListener(injectSite);

function injectSite(data) {
    // get custom configuration for this URL in the background page.
    var site_conf = getSiteConfiguration(data.url);

    if (site_conf)
    {
        chrome.tabs.executeScript({ code: 'PARAMS = ' + JSON.stringify(site_conf) + ';' });
        chrome.tabs.executeScript({ file: 'site_injection.js' });
    }
}

In the content script page (site_injection.js)

// read config directly from background
console.log(PARAM.whatever);
like image 37
Eloims Avatar answered Sep 20 '22 11:09

Eloims