使用document.location=file_url.mp3触发从JS下载-不正确

Using document.location=file_url.mp3 to trigger download from JS - incorrect?

本文关键字:JS 下载 不正确 mp3 location document file url 使用      更新时间:2023-09-26

我在这里查看一些遗留代码,以及它触发.mp3文件播放的方式如下:

document.location = file_url.mp3;  

这反过来会提示用户下载或播放文件(取决于平台)。我只是觉得这是非常不正确的方式,允许用户播放.mp3文件。有人能具体说明为什么这种方法是错误的吗?

试试这个

$('a').click(function(e) {
e.preventDefault();  //stop the browser from following
window.location.href = 'file_url.mp3';
});
<a href="no-script.html">Download</a>

使用preventDefault

您可以创建一个空的隐藏HTMLdiv

<div id="player" style="display:none"></div>

然后添加这个JavaScript

function playMp3(stop) {
   var div = document.getElementById('player');
   if (stop) {
       div.innerHTML = '';
   } else {
       div.innerHTML = '<audio autoplay><source src="fule_url.mp3" type="audio/mpeg"></audio>';
   }
}

现在播放文件

playMp3();

停止播放呼叫

playMp3(1);