Menü schliessen
Created: December 19th 2024
Last updated: December 19th 2024
Categories: Common Web Development,  IT Development,  JavaScript Development
Author: Tim Fürer

JavaScript: How to Trigger Download through Code

Tags:  guide,  Javascript
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

With a little trickery, one can make the browser trigger a file download through JavaScript. The idea is that we virtually create an anchor tag, set its href to the URL of the file, and give it the download attribute. Then we programmatically execute a click upon it using its .click() method.

Here's a function that follows and lets us simplifies this process:

function download(href, filename = '') {
    const a = document.createElement('a');

    a.href = href;

    a.download = filename;

    a.click();
}

Usage:

download('https://example.com/foobar.file');