Avoid using .onload
, .onclick
, etc. in a userscript. (This is considered bad practice even on a regular web page).
The reason for this recommendation is that userscripts are restricted within a sandbox ("isolated environment"), which limits the ability to set or access page-wide JavaScript objects in a Chrome userscript or content-script.
Instead, always opt for using addEventListener()
(or similar functions from libraries like jQuery's .on()
). Additionally, it is advisable to establish load
listeners prior to injecting <script>
elements into the DOM.
If you need to reach variables in the page scope (such as B
here), you will need to insert code that facilitates this operation. (Alternatively, you can consider switching to Tampermonkey and utilizing unsafeWindow
, though there have been reported issues with this approach due to Chrome 29 compatibility problems.)
Consider employing something along these lines:
addJS_Node (null, "http://localhost/test/js/load.js", null, executeAfterLoad);
function executeAfterLoad () {
addJS_Node ("console.log (B);");
}
//-- The addJS_Node function follows standard practices
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 targetElement = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
targetElement.appendChild (scriptNode);
}
Alternatively:
addJS_Node (null, "http://localhost/test/js/load.js", null, executeAfterLoad);
function executeAfterLoad () {
addJS_Node (null, null, myScriptThatUsesPageJS);
}
function myScriptThatUsesPageJS () {
console.log (B);
//--- ADDITIONAL FUNCTIONALITY CAN BE INCLUDED HERE.
}
... ...