Ladislav M
Ladislav M

Reputation: 2187

Chrome extension - loading file from localhost to content_scripts

I'm developing Chrome Extension and I need to load a javascript file to content scripts, but that file is being served via webpack-dev-server. So it's approachable only on localhost.

I tried to change my manifest.json:

"content_scripts": [
    {
      "matches": [
        "http://*/*",
        "https://*/*"
      ],
      "js": [
        "http://localhost:3000/scripts/content_bundle.js"
      ],
      "run_at": "document_end",
      "all_frames": false
    }

But then I got an error in Chrome Extensions window:

enter image description here

Upvotes: 4

Views: 3727

Answers (1)

woxxom
woxxom

Reputation: 73506

Only local files can be specified in "content_scripts" section.

Solution:

  • add "permissions": ["http://localhost:3000/scripts/*", "tabs"] to manifest.json
  • download the script using XMLHttpRequest (there are many examples) in your background script (or better an event page script) when needed
  • save it in chrome.storage.local or localStorage (so you can load it on every extension start from the storage without redownloading)
  • inject the script:
    • add a tabs.onUpdated listener and inject the script using tabs.executeScript
    • alternatively use declarativeContent API with RequestContentScript action (despite the warning on the doc page it should be actually supported in the Stable channel but of course do some tests first).

Upvotes: 4

Related Questions