I'm trying to inject a remote script as the content script in Chrome extension, but I feel like I'm running into the murky (at least to me) area of Chrome execution environment.
I want to use jQuery's $.getScript
for that (and other) purposes.
Here's the injection code (brilliantly suggested here):
// inject jQuery
chrome.tabs.executeScript(null, { file: "js/jquery.js" }, function() {
// inject remote script with jQuery
chrome.tabs.executeScript(null, { code: '$.getScript("https://mysite.com/myremotescript.js", function(){ })' });
});
Here's the remote script myremotescript.js
- it's simple:
$("body").css("backgroundColor", "green");
The error is: "$ is not defined"
The $
referred in the error seems to be that of the myremotescript.js
function, because it works if myremotescript.js
is changed to:
document.body.style.backgroundColor = "green";
It appears that it's not only $
that is not defined. If I change myremotescript.js
to:
function Do(){
document.body.style.backgroundColor = "green";
}
and then execute Do() from the callback of $.getScript
:
chrome.tabs.executeScript(null, {
code: '$.getScript("https://mysite.com/myremotescript.js", function(){ Do(); })'
});
The error is then: "Do is not defined"
Any ideas/explanation/suggestions?
EDIT: SOLUTION: Following @Rob-W answer, it worked. The only quirk that I needed to add to get $.get()
not to error out was to mark the data type as "text". Also, I didn't need to do eval
, since executeScript
can accept code-as-text:
$.get("https://mysite.com/myremotescript.js", null, null, "text")
.done(function(remoteCode){
chrome.tabs.executeScript(null, { code: remoteCode }, function(){
chrome.tabs.executeScript(null, { code: "Do();" });
});
})