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??

neaumusic
  • 10,027
  • 9
  • 55
  • 83
  • tried putting it in manifest `"web_accessible_resources": ["jquery.js"]` but no success – neaumusic Dec 01 '15 at 07: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. – wOxxOm Dec 01 '15 at 09:09
  • i have a feeling chrome is denying the resource and swallowing the error – neaumusic Dec 01 '15 at 09:35
  • I don't understand. What actually happens when you debug it? – wOxxOm Dec 01 '15 at 09:39
  • 1
    See [Google Chrome Javascript Debugger and Content Scripts](http://stackoverflow.com/q/895751) 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](http://stackoverflow.com/a/9517879) – wOxxOm Dec 01 '15 at 10:13
  • Possible duplicate of [Building a Chrome Extension - Inject code in a page using a Content script](http://stackoverflow.com/questions/9515704/building-a-chrome-extension-inject-code-in-a-page-using-a-content-script) – Teepeemm Dec 01 '15 at 15:02
  • What are you TRYING to do? Use jQuery in your own content script code? Inject jQuery into the page's code? – Xan Dec 02 '15 at 11:33
  • Yea implementing a legacy, jQuery dependent script, which should only be applied when window.location.hostname matches – neaumusic Dec 02 '15 at 21:16

0 Answers0