如果您的意思是使文件下载到用户的计算机上,则此代码将在 Chrome 扩展内容脚本或 JS 脚本和常规网页中运行:
首先,您可以通过简单地将"download" attribute 添加到锚标记来使文件在没有任何JS 的情况下下载。使用此标记,将下载该 URL,而不是导航到“href”属性中的 URL。
<a href="http://website.com/example_1.txt" download="saved_as_filename.txt" id="downloader">
static download link</a>
动态更新 URL:
var theURL = 'http://foo.com/example_2.txt';
$('#downloader').click(function() {
$(this).attr('href',theURL);
});
如果您希望通过点击链接以外的其他方式启动下载,您可以模拟点击链接。请注意, .trigger() 不适用于此目的。相反,您可以使用document.createEvent:
$('#downloader').css('display','none');
function initiateDownload(someURL) {
theURL = someURL;
var event = document.createEvent("MouseEvent");
event.initMouseEvent("click", true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null);
// dispatch event won't work on a jQuery object, so use getElementById
var el = document.getElementById('downloader');
el.dispatchEvent(event);
}
initiateDownload('example_3.txt');