1

I don't want to include jQuery on every page by listing it in the manifest

In the console, this works fine, but I can't dynamically include jQuery in a content script

No idea why


  1. Put these two files in a folder (content.js and manifest.json)
  2. Go to chrome:extensions in omnibox (url bar)
  3. Load Unpacked Extension
  4. Select Folder
  5. Go to any page and CMD+Shift+R reload without cache

Check out the console and see jQuery is undefined


content.js

if (document.readyState === "complete") {
    appendJQuery();
} else {
    document.addEventListener("DOMContentLoaded", appendJQuery);
} function appendJQuery () {
    var jq = document.createElement("script");
    window.document.querySelector("head").appendChild(jq);
    jq.onload = function () {
        console.log(typeof $); // $ is not defined ?????
    }
    jq.src = "https://code.jquery.com/jquery-2.1.1.min.js";
}

manifest.json

{
    "manifest_version": 2,
    "name": "Sample",
    "short_name": "Sample",
    "version": "1.1",
    "permissions": ["tabs", "http://*/*, https://*/*", "*://*/*", "<all_urls>"],
    "content_scripts": [{
        "matches": ["*://*/*", "http://*/*", "https://*/*", "file://*/*"],
        "js": ["content.js"],
        "run_at": "document_start"
    }]
}

then jQuery is undefined......... wtf??? anyone know why??

8
  • tried putting it in manifest "web_accessible_resources": ["jquery.js"] but no success Commented Dec 1, 2015 at 7:26
  • 1
    Use the debugger to debug the content script and see what actually happens, don't guess. My guess would be that at the start there's no head element yet. Also page CSP may disallow that url. Commented Dec 1, 2015 at 9:09
  • i have a feeling chrome is denying the resource and swallowing the error Commented Dec 1, 2015 at 9:35
  • I don't understand. What actually happens when you debug it? Commented Dec 1, 2015 at 9:39
  • 1
    See Google Chrome Javascript Debugger and Content Scripts and also instead of using an external resource load it from your extension locally, see method 1 in Building a Chrome Extension - Inject code in a page using a Content script Commented Dec 1, 2015 at 10:13

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.