In this article, I will introduce how to download text files etc. with JavaScript on the front end (browser side). The related resources are as follows.
The workflow is as follows.
- Preparation for coding
- Coding
- Operation check
Run the following command in the terminal to prepare for coding.
mkdir javascript-download-file
cd javascript-download-file
touch index.html main.js
Open index.html in the editor and enter the following content.
Open main.js in the editor and enter the following content.
The points are as follows:
- After creating the blob of the data to be downloaded, call the URL.createObjectURL function to create the object URL.
- Call the document.createElement method to dynamically generate the anchor (a tag) and use the anchor.setAttribute method to set the object URL in the href attribute. Also, set the file name at the time of download in the download attribute.
- After creating an instance of MouseEvent, call the anchor.dispatchEvent method and click anchor in a pseudo manner.
Open index.html in the browser. The following commands are useful for macOS.
open index.html
Check that the file download starts when you click the "Download" button in the web page.
The web pages that I referred to in creating this article are as follows.
The method described in this article has been confirmed to work with the following browsers of macOS Monterey 12.0.1.
- Google Chrome 101.0.4951.54
- Firefox 100.0
- Safari 15.1
For a similar article, phi wrote JavaScript tips - How to download a file with dynamically entered content.
Regarding the difference from this article, the method described in phi's article sets the object URL in the href attribute of the a tag in HTML, whereas the method described in this article uses JavaScript. The point is that the a tag is dynamically generated in. The approach is different, but the results are similar. The method described in phi's article is simpler and has less code. On the other hand, the method described in this article has a lot of code, but it can be used not only for the a tag but also for the button tag.
MouseEvent can only be generated by the click event of the a tag or button tag ... I thought that I could do it normally when I tested it with the load event of the window lol I feel like I could not do it before I do, but am I misunderstanding something? If you have any details, I would appreciate your guidance and comments, and other comments are welcome. Thank you for reading!