Martti Laine
Martti Laine

Reputation: 12995

Communicate with a page script from a content script in a Chrome extension

I'm loading a content script (1.js), which at some point appends a <script>-element, that point to a file inside the extension (2.js). 2.js can't be included as a content script.

Is there a way to use a variable defined inside 2.js from 1.js?

Upvotes: 0

Views: 617

Answers (2)

Martti Laine
Martti Laine

Reputation: 12995

I figured this out. A bit dirty, but works with a dynamic object, which I had in question.

I simply added all the code by injecting it to the page. Here's my content script:

var path = document.createElement('div');
path.id = 'codearea-path';
path.innerHTML = chrome.extension.getURL('/');
path.style.display = 'none';
document.body.appendChild(path);

var script = document.createElement('script');
script.src = chrome.extension.getURL('1.js');
document.head.appendChild(script);

Then I used the same kind of code to include 2.js inside 1.js.

Upvotes: 0

apsillers
apsillers

Reputation: 116040

Use message passing between your background page and content script. The background page holds the value (either by loading 2.js as a script, or by having 2.js be the application's background script itself) and listen for incoming messages with chrome.extension.onRequest.addListener. The content script sends a request, and the content script sends a response with the desired value.

Upvotes: 1

Related Questions