Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Chrome Extension development, how do I pass a variable from background.js to a content script that embedded as a script node?

Update: I am sorry that I wasn't clear about my case. The content script is not literally content script but a js file embedded into the page via the createElement method.

It's something like:

// this is "content.js"
var scriptElement = document.createElement('script');
scriptElement.src = 'chrome-extension://' + chrome.runtime.id + '/js/page-inject.js';
(document.head || document.documentElement).appendChild(scriptElement);

I want to use it in "page-inject.js", not the "content.js"

I thought it was very simple but failed after hours of retrying and searching.

I have a background.js like this:

chrome.tabs.query({active: true, currentWindow: true}, 
function(tabs) {
  chrome.tabs.executeScript(tabs[0].id, {
    code: 'window.my_var = 123'
  }, function() {
    chrome.tabs.executeScript(tabs[0].id, {file: 'js/content.js'});
  });
});

After this, when I type "window.my_var" in the console of that page. It's not working. The wanted "123" is not showing up.

If I replace the code: 'window.my_var = 123' to alert(123), it works. But what I need is just to pass a variable from my background script (background.js) to the web page that my extension injected into.

Is there anything wrong with my try?

like image 773
AGamePlayer Avatar asked Mar 10 '18 14:03

AGamePlayer


1 Answers

As @wOxxOm already pointed out you how to see the variable inject using the chrome.tabs.executeScript in the web page console by changing the Top in the console.

There is another way you can easily pass values from background to content script using messaging.

Se below a simple example:

manifest.json

{
  "name": "test",
  "version": "0.0.1",
  "manifest_version": 2,
  "description": "Test ",
  "background": {
    "scripts": [
      "background.js"
    ]
  },
  "browser_action": {
    "default_title": "Test "
  },
  "permissions": [
    "*://*/*",
    "tabs"
  ], "content_scripts" : [{
            "matches" :  ["*://*/*"],
            "js" : ["content.js"]
        }]
}

background.js

  chrome.browserAction.onClicked.addListener(function(){
       chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            chrome.tabs.sendMessage(tabs[0].id, {data: "some value"});
        });
    });

content.js

chrome.extension.onMessage.addListener(handleMessage);
function handleMessage(request) {
    console.log(request.data);
}
like image 117
elegant-user Avatar answered Oct 17 '22 15:10

elegant-user