早期瀏覽器不支援 <a download>,利用隱藏 <iframe> 模擬下載:創建 iframe → 設 src 為文件 URL → 在 iframe 執行 execCommand('SaveAs')。
<a href="a.txt" id="dlLink" onclick="return saveFile()">點擊下載</a>
<script>
function saveFile(){
const link = document.getElementById('dlLink');
const iframeName = 'dlFrame';
// 1. 確保 iframe 存在
let iframe = window.frames[iframeName];
if(!iframe){
const el = document.createElement('iframe');
el.name = iframeName;
el.style.display = 'none';
document.body.appendChild(el);
iframe = window.frames[iframeName];
// 給 iframe 一點時間初始化
return setTimeout(saveFile, 1);
}
// 2. 觸發下載
iframe.location.href = link.href;
try{
iframe.document.execCommand('SaveAs');
}catch(e){
// 非 IE 不支援 SaveAs,現代瀏覽器直接下載
}
return false; // 阻止 a 標簽默認跳轉
}
</script>
<a href="file.pdf" download="自定義文件名.pdf">下載</a>
download 屬性指定保存文件名,同源策略下直接觸發下載。Content-Disposition: attachment 或代理下載。URL.createObjectURL 可下載動態生成內容(如 Canvas 圖片、JSON 導出)。iframe 方案僅用於極舊 IE 維護。新項目直接用 <a download> + Blob 下載,代碼簡潔、無副作用、標準化。