Home > Software design >  How to download .js file by JavaScript from an url?
How to download .js file by JavaScript from an url?

Time:12-24

I know this question is asked hundreds of time in this forum, But I'm trying to download a .js file from an url in my Vue 2 application, but it's not working. Here is what I'm trying:

downloadScript() {
      ApiService.post(`url`).then((res) => {    // axios
        try {
          // Create a new link
          const url = window.URL.createObjectURL(new Blob([res.data.path]));
          const anchor = document.createElement("a");
          anchor.href = url;.js";
          anchor.setAttribute("download", "script.js");
          document.body.appendChild(anchor);
          anchor.click();
        } catch {
         //
        }
      });
    },

This downloads a file which consists nothing but the url I've provided to the axios post request.

I'm getting API response like following:

{
    "success": true,
    "path": "https://something.com/files/iq-return.min.js"
}

I've to donwload the script in a file from the path

CodePudding user response:

new Blob([res.data.path]) creates a Blob (which is sort-of-like-a-file) containing the text in the string you pass it.

Since that text is a URL, the file you download is a text file containing that URL.

If you want to create a Blob containing the JavaScript source code, then you need to get the JS source code. Make an HTTP request to the URL (e.g. with fetch) and put the response body in the Blob.

(Aside: don't append .js to the generated URL with you set href, that modifies the contents of the file!)

This will, of course, require permission from CORS if this is a cross-origin request.

If it isn't a cross-origin request then you can just set the href attribute to res.data.path without leaping through all these hoops.

  • Related