Search code examples
javascriptjquerygoogle-chromedomgoogle-chrome-extension

When injecting an HTML template with a Google Chrome extension with various scripts, jQuery doesn't seem to import


To elaborate, I am injecting and loading an HTML template in my Google Chrome extension like this:

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
        // Typical action to be performed when the document is ready:
            
            var PBSKPage = xhttp.responseText;
            document.querySelector('html').innerHTML = "";
            loadPBSKPage();
            function loadPBSKPage() {
                
                document.querySelector('html').innerHTML = PBSKPage;
            }
        }
    };
function insertAndExecute() {
    var scripts = Array.prototype.slice.call(document.getElementsByTagName("script"));
    for (var i = 0; i < scripts.length; i++) {
        if (scripts[i].src != "") {
            var tag = document.createElement("script");
            tag.src = scripts[i].src;
            document.getElementsByTagName("head")[0].appendChild(tag);
        }
        else {
            eval(scripts[i].innerHTML);
        }
    }
}

And in my HTML template, I clearly put the script tag that requests jQuery before the jQuery-reliant scripts:

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script>window.jQuery || document.write('<script src="chrome-extension://niabfndainielhgpcjenbpodannhfofj/2015/pbsk_resources/wildkratts/js/vendor/jquery-1.11.0.min.js"><\/script>')</script>
        <script src="chrome-extension://niabfndainielhgpcjenbpodannhfofj/2015/pbsk_resources/wildkratts/js/vendor/jquery.nivo.slider.pack.js" type="text/javascript"></script>
        <script src="chrome-extension://niabfndainielhgpcjenbpodannhfofj/2015/pbsk_resources/wildkratts/js/vendor/jquery.touchSwipe.min.js" type="text/javascript"></script>
        <script src="chrome-extension://niabfndainielhgpcjenbpodannhfofj/2015/pbsk_resources/wildkratts/js/vendor/retina.min.js"></script>
...

jQuery doesn't seem to import, and when the JS files are executed, the browser always spits out an Uncaught TypeError on something that would be defined if jQuery was imported.

So what do I do? Is this because of CSP? Is it because of the insertAndExecute() function? Is it because of the intrinsic inner workings of Google Chrome extensions? I suppose I could just paste the jQuery JS into each of the jQuery-reliant JS files, but that wouldn't be very efficient. Does anyone have a solution to this?


Solution

  • I don't have a high enough rep to comment on the answer above mine, but bundling jQuery with your code and the libraries you wish to use should do the trick. That said, it might be a good idea to use a more up-to-date version of jQuery since it's received a number of significant security patches since version 1.11.