max pleaner
max pleaner

Reputation: 26788

Trigger click on link with 'download' attribute

I have some links like this:

<a class="download-link" href="/some/file.mp3" download="file.mp3">download></a>

When this link is clicked, the file is downloaded with no prompt.

I'm trying to make a "download all" button, but I'm failing because it's seemingly not possible to trigger on a click on these links.

For example:

$($("a[download]")[0]).trigger("click")
// this shows no error, but the file is not actually downloaded

According to this article from 2013, it is possible to trigger clicks on download links in Chrome. Has this been deprecated? Is there an alternative approach?

By the way I'm using Chrome 52. Ideally I'd find something that works on Chrome for Android as well.

My suspicion is that it is not possible, because then websites could download all sorts of malicious files if they want to. However since a 'download all' button is a common use case, I'm wondering if there is some working approach. I don't need to trigger the initial click - the "download all" button will be clicked by the user, and this will trigger the subsequent clicks.


To try it your self, go to https://maxpleaner.github.io/my_music/ and type the following script in the console: $($("a[download]")[0]).trigger("click")

Upvotes: 3

Views: 6141

Answers (2)

rvighne
rvighne

Reputation: 21917

I am not sure how jQuery does it, but the following vanilla JavaScript successfully downloads every link on the page:

for (let link of document.querySelectorAll('a[download]'))
    link.click();

Chrome then prompts me if I want to download multiple files, and it works.

Google Chrome download multiple files prompt

Though you may want to warn users before doing this, as it makes the browser somewhat sluggish.

Upvotes: 8

Vijai
Vijai

Reputation: 2507

You have missed a dot for the CLASS in ".download-link"

$($(".download-link")[0]).trigger("click")

Upvotes: -2

Related Questions