0

I am writing up a ContentScript for a Chrome Extension. In the script, I want to import a javascript (actually a JS and a CSS) and initiate a class from that script.

To ensure the Javascript is properly loaded, I followed the guidance from several SO posts like this, this and this.

var link = document.createElement( "link" );
document.body.appendChild(link);

link.onload = function(){
    console.log("link loaded");

    var script = document.createElement('script');
    document.body.appendChild(script); //or something of the likes

    script.onload = function () {

        ...
        console.log("script loaded");
        // somehow ContentTools is undefined even after the script is loaded
        editor = ContentTools.EditorApp.get();
        editor.init('*[data-editable]', 'data-name');   
        console.log("all finished")
    };
    script.src = "https://....min.js";

};    
link.href = "https://....min.css";
link.type = "text/css";
link.rel = "stylesheet";

I am assuming that this way of callling ContentTools.Editor at the innermost of the nested onload is a good way of guarantee that the proper CSS and JS dependencies are properly loaded. However, when I run it as a Chrome Extension inside the contentscript, it errors out with Undefined ContentTools as referenceerror but I saw message "link loaded" and "script loaded".

Clearly, ContentTools are loaded and defined (see the screenshot). And if I execute the whole script directly in the console, everything works. Looks like the root cause is only in Chrome Extension content script, somehow the editor = ContentTools... got called before the script is fully loaded.

enter image description here

As it is only an error as a Chrome extension but not in the Console, I am a bit lost here. jQuery related solution is also welcome here.

B.Mr.W.
  • 16,522
  • 30
  • 96
  • 156
  • The content scripts run in the *isolated world*, and normal DOM scripts run in the page world. You can't access the JS variables across worlds. You'll need to add another DOM script that will access the stuff. More details: [Insert code into the page context using a content script](//stackoverflow.com/a/9517879) – wOxxOm Jul 03 '19 at 16:03
  • All the code above sits in click.js which is included and got executed by popup.js by a onclick event. Isn't it sufficient? Shall I put the `click.js` into the target DOM (page world) within popup.js in addition to executeScript? Thanks – B.Mr.W. Jul 03 '19 at 16:12
  • It's still the same isolated world of the content script so no it won't do. – wOxxOm Jul 03 '19 at 16:19

0 Answers0