Sometimes, we want to force the download of a link with JavaScript.
In this article, we’ll look at how to force the download of a link with JavaScript.
How to force the download of a link with JavaScript?
To force the download of a link with JavaScript, we can create a hidden link and click it programmatically.
For instance, we write:
<button>
download
</button>
to add a button.
Then we write:
const download = document.querySelector("button");
download.onclick = () => {
const anchor = document.createElement("a");
anchor.href =
"https://file-examples-com.github.io/uploads/2018/04/file_example_AVI_480_750kB.avi";
anchor.target = "_blank";
anchor.download = "example.pdf";
anchor.click();
};
to select the button with document.querySelector
.
Then we set its onclick
property to a function that creates the link with document.createElement
.
And we set the href
to the file we want to download.
And we set the download
property to the file name of the file.
Finally, we call click
to click it to start the download.
Conclusion
To force the download of a link with JavaScript, we can create a hidden link and click it programmatically.