Is there any way to load a local JS file dynamically?

google-chrome, javascript

Solution

In Chrome, you can create an extension that holds all of the local files that you need to load. It will make your files accessible via `chrome-extension://...` instead of `file://...`

Make a file named `manifest.json` in a new folder and fill it with:

{
  "name": "File holder",
  "manifest_version": 2,
  "version": "1.0",
  "web_accessible_resources": ["test.js", "other.js", "yetanother.js"]
}

Then, put all the scripts you want to load in that new directory, and make sure they are included in the `web_accessbile_reources` manifest list. Load the extension by going to `chrome://extensions`, enabling `Developer Mode`, and selecting the new folder with `Load unpacked extension...`.

Now you can access all the files in your extension directory using `chrome-extension://[app_id]/[file_name]`, where "`app_id`" is the hash listed for the extension on the `chrome://extensions` page. Note that because the protocols and hostnames differ from where you've doing your actual work (unless you decide to do all your development in the extension folder, which might be acceptable to you), the extension resources are cross-domain and can only be loaded via `<script>` tag.

Now from the console, you can do:

var s = document.createElement("script");
s.src = "chrome-extension://aefigdoelbemgaedgkcjpcnilbgagpcn/test.js";
document.body.appendChild(s);

(Assuming your file is `test.js` and your app id is `aefigdoelbemgaedgkcjpcnilbgagpcn`.)

It's a quite bit to type, I know, but perhaps you can store the `chrome-extension://[app_id]` part as a shorthand variable?

Problem

For development purposes, I'd like to be able to easily load locally-stored scripts into the browser instead of having to copy-paste to the console. Creating a new `<script>` element isn't working, it gives a `Not allowed to load local resource: file://....` error (in Chrome). Also, creating a userscript won't work--I'd have to re-install it every time I make an edit. Is there an alternative way to easily load a local script via a bookmarklet/etc?

Original source

Related problems