Anton Tarasenko
Anton Tarasenko

Reputation: 8475

How to get variables from content scripts in a Chrome extension?

I'm trying to modify Google's sample code for code injections. File manifest.json includes a background script:

  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },

and I add a content script:

  "content_scripts": [
    {
      "matches": ["*://*/*"],
      "js": ["filter.js"]
    }
  ],

Now I want to call function foo() defined in filter.js when the user clicks the extension's button. I do this in background.js:

chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript({
    code: 'foo(testText);'
  });
});

where foo() is defined in filter.js as

function foo(test) {
  alert('Test: ' + String(test));
}
var testText = 'foo';

I can execute the function, but can't pass the testText variable. I get VM3181:1 Uncaught ReferenceError: testText is not defined.

I know I refer to the variable incorrectly, but how to do it right?

Upvotes: 0

Views: 588

Answers (1)

user6105387
user6105387

Reputation:

Take a look at sendMessage and onMessage, examples repurposed from Google:

In background.js:

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.sendMessage(tab.id, {greeting: "foo"}, function(response) {
        console.log(response.farewell);
    });
});

And in filter.js:

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        if (request.greeting == "foo") {
            //your Foo function can be called
            sendResponse({farewell: "bar"});
        }
});

Upvotes: 1

Related Questions