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

后端 未结 3 1513
清歌不尽
清歌不尽 2020-12-14 20:41

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\'r

相关标签:
3条回答
  • 2020-12-14 21:08

    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);
    
    0 讨论(0)
  • 2020-12-14 21:10

    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.

    0 讨论(0)
  • 2020-12-14 21:25

    I thought I'd update this answer for current and future readers.

    According to the Chrome API, chrome.extension.onRequest is "[d]eprecated since Chrome 33. Please use runtime.onMessage."

    See this tutorial from the Chrome API for code examples on the messaging API.

    Also, there are similar (newer) SO posts, such as this one, which are more relevant for the time being.

    0 讨论(0)
提交回复
热议问题