简体   繁体   English

如何使用 JS 触发下载音频链接,而无需浏览器导航到新页面?

[英]How to trigger a download of an audio link using JS, without having the browser navigate to a new page?

I want to write a script that downloads some audio files from a web page.我想编写一个脚本,从 web 页面下载一些音频文件。 Problem is, that simulating the "click" via element.click() doesn't work well, because the browser simply navigates to the URL of that anchor element.问题是,通过 element.click() 模拟“点击”效果不佳,因为浏览器只是导航到该锚元素的 URL 。 For example:例如:

<a href="https://www.somesite.com/someAudioFile.mp3"></a>

const link = document.querySelector('a');

link.click();//Navigates to the url...

What I need, is to be able to collect all those links that I need, and simply trigger the download, without the save-as dialogue appearing我需要的是能够收集我需要的所有链接,并简单地触发下载,而不会出现另存为对话框

Is it possible?可能吗? If so, how?如果是这样,怎么做?

You can add download attribute to element, without javascript您可以将下载属性添加到元素,没有 javascript

<a href="https://www.somesite.com/someAudioFile.mp3" download></a>

Or download with custom name或使用自定义名称下载

<a href="https://www.somesite.com/someAudioFile.mp3" download="music"></a>
link.addEventListener('click', (e) => e.preventDefault());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM