This fantastic answer shows how you can dynamically insert JavaScript into a page from a Chrome extension:
var s = document.createElement('script');
// TODO: add "script.js" to web_accessible_resources in manifest.json
s.src = chrome.extension.getURL('script.js');
s.onload = function() {
this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s);
When the onload()
function is called, it's executed in the browser page's isolated world, not the extension's isolated world, right?
Assuming that's correct, I'm having an problem I don't understand.
Inside of my script.js
I have code similar to this:
var globalObj = globalObj || {};
globalObj.method = function () {
console.log('hey!');
};
Then I changed the onload()
function above to:
s.onload = function() {
this.parentNode.removeChild(this);
globalObj.method();
};
But the console shows the error:
Uncaught ReferenceError: globalObj is not defined
Why isn't globalObj
defined inside of the onload()
function?