瀏覽器對 <a download> 的支援雖已普及,但針對二進制文件、跨域資源或需要觸發下載而不跳轉頁面的場景,動態創建一個隱藏的 <iframe> 並將其 src 指向文件地址,是一種經典且兼容性極佳的方案。
<script>
function download() {
// 文件下載地址(示例為音樂鏈接)
var url = "https://music.baidu.com/data/music/file?link=https://zhangmenshiting.baidu.com/data2/music/13618994/13618995183600128.mp3?xcode=48d4a720fcd9a974586066d0145f7207";
// 將隱藏 iframe 的 src 設置為目標 URL,瀏覽器會自動觸發下載
document.getElementById("ifile").src = url;
}
</script>
<a href="#" onclick="download()">點擊下載</a>
<iframe id="ifile" style="display:none"></iframe>
style="display:none" 讓 iframe 不佔據頁面空間,用戶無感知。iframe.src 會讓瀏覽器發起 GET 請求;若響應頭包含 Content-Disposition: attachment,瀏覽器會彈出下載對話框而非在 iframe 中顯示內容。download 屬性或 Blob/Object URL。若文件內容由前端生成(如導出 CSV、JSON),可結合 URL.createObjectURL 與 <a download>,更為現代:
function downloadText(filename, text) {
const blob = new Blob([text], {type: 'text/plain;charset=utf-8'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url); // 釋放內存
}
Access-Control-Allow-Origin 及 Content-Disposition,否則瀏覽器可能攔截或直接在新標籤頁打開。fetch + ReadableStream 監聽進度。