触发点击带有“下载"属性的链接 [英] Trigger click on link with 'download' attribute

查看:44
本文介绍了触发点击带有“下载"属性的链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些这样的链接:

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

点击此链接后,文件将在没有提示的情况下下载.

我正在尝试制作全部下载"按钮,但我失败了,因为点击这些链接似乎不可能触发.

例如:

$($("a[download]")[0]).trigger("click")//这显示没有错误,但实际上并未下载文件

根据

尽管您可能想在执行此操作之前警告用户,因为它会使浏览器变得有些迟钝.

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")

解决方案

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.

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

这篇关于触发点击带有“下载"属性的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆