I am building a Chrome Extension and when clicked on the toolbar icon, I am executing background.js
, and in background.js
I am running execute script. Like this:
chrome.tabs.executeScript(null, { file: "libs/jquery.min.js" }, function() {
chrome.tabs.executeScript(null, { file: "scripts/myScript.js" })
});
In myScript.js
, I can confirm that it has executed jQuery and running my script too.
myScript.js:
console.log('test');
$(document).ready(function() {
console.log('jQuery test');
})
They both work
At this point, I am trying to achieve a variable that is inside the web page (not written by me); let's say it is var helloWorld = "the content"
.
If I try in the console (dev tools), console.log(helloWorld)
, it works. However, if I try in myScript.js
, it says:
$(document).ready(function() {
console.log(helloWorld)
setTimeout(function() {
console.log(helloWorld)
}, 1500)
})
Uncaught ReferenceError: helloWorld is not defined
I have seen some workaround for content script approach, but I couldn't make it work for the executeScript approach. How can I access the helloWorld
variable inside myScript.js
?
I tried using Predator's approach. Here are the codes:
injected.js:
chrome.runtime.sendMessage("njfhnpgecmbmbipcjpkkglbkpcbjammb", {varName: "test"});
// I tried returning a string first
background.js
chrome.tabs.executeScript(null, { file: "libs/jquery.min.js" }, function() {
chrome.tabs.executeScript(null, { file: "scripts/myScript.js" })
});
chrome.runtime.onMessageExternal.addListener( function(message, sender, sendResponse){
console.log(message.varName);
if( message.varName !== undefined ){
console.log(message.varName);
}
});
manifest:
"background": {
"scripts": ["scripts/background.js"],
"persistent": true
},
according to your first answer, myScript.js
:
$(document).ready(function() {
setTimeout(function() {
var s = document.createElement('script');
s.src = chrome.extension.getURL('scripts/fetcher.js');
s.onload = function() {
this.remove();
};
(document.head || document.documentElement).appendChild(s);
}, 500)
})
according to your updated answer, myScript.js
:
function exec(fn) {
var script = document.createElement('script');
script.setAttribute("type", "application/javascript");
script.textContent = '(' + fn + ')();';
document.body.appendChild(script); //run the script
document.body.removeChild(script); //clean up
}
background.js
is not catching the message