8

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?

AGamePlayer
  • 7,404
  • 19
  • 62
  • 119

2 Answers2

8

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);
}
Aefits
  • 3,399
  • 6
  • 28
  • 46
  • Sorry for the late reply. I have updated my question. – AGamePlayer Mar 21 '18 at 13:10
  • Thanks very much for the answer. However, what I'm looking for is a way to make the variables working in a manually added js file (to the page). My current workaround is not to use this way to add js file on the page. But if it'd work, the code would be much easy to maintain since they are all in that separate file (`page-inject.js`) that can be added on the page at any time rather than a `content.js` file that should be added to the page by default of the extension rule. – AGamePlayer Mar 23 '18 at 11:01
-1

chrome.extension.getBackgroundPage() will return the global window object of the background page. You can access scripts and any data in the background worker.

Example

const backgroundDOMWindow = chrome.extension.getBackgroundPage();
const myGlobalVariable = backgroundDOMWindow.window['myGlobalVariable'];

Adding script to global background object "background.js"

document.write(
'<script src="main.js"></script>'+
'<script src="main2.js"></script>'
);
Fuji
  • 28,214
  • 2
  • 27
  • 29
  • `getBackgroundPage` returns the JavaScript 'window' object for the background page running inside the current extension and not in the content script. – Aefits Mar 21 '18 at 10:15