I want to load another script file, in a site, using a userscript.
But, the js.onload
event doesn\'t work correctly.
The userscript file:
Never use .onload
, .onclick
, etc. from a userscript. (It's also poor practice in a regular web page).
The reason is that userscripts operate in a sandbox ("isolated world"), and you cannot set or use page-scope javascript objects in a Chrome userscript or content-script.
Always use addEventListener()
(or an equivalent library function, like jQuery .on()
). Also, you should set load
listeners before adding <script>
nodes to the DOM.
Finally, if you wish to access variables in the page scope (A
in this case), you must inject the code that does so. (Or you could switch to Tampermonkey and use unsafeWindow
, but Chrome 27 is causing problems with that.)
Use something like:
addJS_Node (null, "http://localhost/test/js/load.js", null, fireAfterLoad);
function fireAfterLoad () {
addJS_Node ("console.log (A);");
}
//-- addJS_Node is a standard(ish) function
function addJS_Node (text, s_URL, funcToRun, runOnLoad) {
var D = document;
var scriptNode = D.createElement ('script');
if (runOnLoad) {
scriptNode.addEventListener ("load", runOnLoad, false);
}
scriptNode.type = "text/javascript";
if (text) scriptNode.textContent = text;
if (s_URL) scriptNode.src = s_URL;
if (funcToRun) scriptNode.textContent = '(' + funcToRun.toString() + ')()';
var targ = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
targ.appendChild (scriptNode);
}
Or perhaps:
addJS_Node (null, "http://localhost/test/js/load.js", null, fireAfterLoad);
function fireAfterLoad () {
addJS_Node (null, null, myCodeThatUsesPageJS);
}
function myCodeThatUsesPageJS () {
console.log (A);
//--- PLUS WHATEVER, HERE.
}
... ...