You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JavaScript设置链接download属性仅部分生效问题

自动下载时download属性不生效的解决方案

问题说明

点击按钮后启动10秒倒计时,倒计时结束后自动下载文件,同时设置手动下载链接的download属性。目前手动点击链接时download属性可正常生效,但通过window.location.href触发自动下载时,该属性不生效,无法指定下载文件名。

问题原因

window.location.href = 下载地址的方式本质是页面跳转,浏览器不会识别并应用download属性;只有用户主动触发带有download属性的<a>标签点击事件时,浏览器才会强制触发下载并使用指定的文件名。

解决方法

创建一个隐藏的<a>标签,设置好目标文件地址和download属性,通过代码模拟点击这个标签来触发自动下载,这样就能让download属性生效。

修改后的代码

JavaScript代码

const download = document.querySelector('.download-btn');
const countdown = document.querySelector('.countdown');
const pleaseWaitText = document.querySelector('.pleaseWait-text');
const manualDownloadText = document.querySelector('.manualDownload-text');
const manualDownloadLink = document.querySelector('.manualDownload-link');
let timeLeft = 10;

download.addEventListener('click', () => {
  download.style.display = "none";
  countdown.innerHTML = `Download will begin automatically in <span>${timeLeft}</span> seconds`;

  const downloadTimer = setInterval(() => {
    timeLeft--;
    countdown.innerHTML = `Download will begin automatically in <span>${timeLeft}</span> seconds`;

    if (timeLeft <= 0) {
      clearInterval(downloadTimer);
      pleaseWaitText.style.display = "block";
      const downloadHref = "https://tuqut.com/jsdn12enda21.pdf";
      const targetFileName = "work.pdf";

      // 处理手动下载链接
      manualDownloadLink.href = downloadHref;
      manualDownloadLink.setAttribute("download", targetFileName);

      // 创建隐藏a标签实现自动下载并应用download属性
      const tempLink = document.createElement('a');
      tempLink.href = downloadHref;
      tempLink.download = targetFileName;
      tempLink.style.display = 'none';
      document.body.appendChild(tempLink);
      tempLink.click();
      document.body.removeChild(tempLink);

      setTimeout(() => {
        pleaseWaitText.style.display = "none";
        manualDownloadText.style.display = "block";
      }, 1000);
    }
  }, 1000);
});

HTML代码

<div class="download-container">
  <a href="#" class="download-btn">Download files <i class="fas fa-download"></i></a>
  <div class="countdown"></div>
  <div class="pleaseWait-text">Please wait ...</div>
  <div class="manualDownload-text">
    If the download didn't start automatically, <a href="#" class="manualDownload-link" target="_top" download="work.pdf">click here</a>
  </div>
</div>

关键修改点

  • 移除window.location.href = download_href的跳转方式,改为创建临时<a>标签模拟点击
  • 临时标签设置download属性后触发点击,确保浏览器强制下载并使用指定文件名
  • 保持手动下载链接的属性设置逻辑不变

内容的提问来源于stack exchange,提问作者hindisong.cc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 00:55:14