Categories
JavaScript Answers

How to open a download window without navigating away from the page with JavaScript?

Spread the love

Sometimes, we want to open a download window without navigating away from the page with JavaScript.

In this article, we’ll look at how to open a download window without navigating away from the page with JavaScript.

How to open a download window without navigating away from the page with JavaScript?

To open a download window without navigating away from the page with JavaScript, we create an anchor element and then click it.

For instance, we write

const filePath = "host/path/file.ext";
const a = document.createElement("a");
a.href = filePath;
a.download = filePath.substr(filePath.lastIndexOf("/") + 1);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);

to call createElement to create an a element.

Then we set its href property to the URL of the file to download.

The download property is set to the file name of the downloaded file.

Then we call click to download the file.

Conclusion

To open a download window without navigating away from the page with JavaScript, we create an anchor element and then click it.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *