Boris Ablamunits
Boris Ablamunits

Reputation: 115

Passing a variable before injecting a content script

I am working on a Chrome Extension that works mainly within a pop-up. I would like the user to enter some text (a string) into an input field in the pop-up, and this string will serve as a "variable" in a script I would like to inject and run on a specific page.

I have tried achieving this by making a content script that will execute the script, using the following well documented way:

var s = document.createElement('script');


s.src = chrome.runtime.getURL('pageSearch.js');
s.onload = function() {
   this.parentNode.removeChild(this);
};

(document.head||document.documentElement).appendChild(s);

Basically, I would like to pass the user's input all the way to the code in pageScript.js before executing the script on the page.

What would be the best way to approach this? I will not be getting any information back to the extension.

Thanks.

Upvotes: 0

Views: 833

Answers (1)

Rob W
Rob W

Reputation: 348972

To pass a variable from the popup to the dynamically inserted content script, see Pass a parameter to a content script injected using chrome.tabs.executeScript().

After getting a variable in the content script, there are plenty of ways to get the variable to the script in the page.

E.g. by setting attributes on the script tag, and accessing this <script> tag using document.currentScript. Note: document.currentScript only refers to the script tag right after inserting the tag in the document. If you want to refer to the original script tag later (e.g. within a timer or an event handler), you have to save a reference to the script tag in a local variable.

Content script:

var s = document.createElement('script');
s.dataset.variable = 'some string variable';
s.dataset.not_a_string = JSON.stringify({some: 'object'});
s.src = chrome.runtime.getURL('pageSearch.js');
s.onload = function() {
   this.remove();
};
(document.head||document.documentElement).appendChild(s);

pageSearch.js:

(function() {
    var variable = document.currentScript.dataset.variable;
    var not_a_string = JSON.parse(document.currentScript.dataset.not_a_string);
    // TODO: Use variable or not_a_string.
})();

Upvotes: 2

Related Questions