4

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

1 Answer 1

4

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).
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. And what would you recommend for background script?
@LadislavMaxa, it should contain the code that actually does the things listed in the answer.
@wOxxOm Interesting approach, I've not seen it documented anywhere. How would you incorporate hot reloading upon changes in the injected .js script? Or does your solution already account for that?
Hot reloading is an unrelated task. This answer in a few words is "download and execute the script".

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.