2025-07-20

[Javascript] 前端直接產生並下載文字檔的做法不用 iframe 改用 Blob+Download

如果你在前端遇過一個需求,讓使用者點一下,就直接下載一段文字

多半會查到一些老方法,像是 iframe + execCommand('SaveAs'),現在改變了..


這邊主要是筆記也就不囉嗦,主要就是呼叫新式瀏覽器的 Blob + <a> 來做到這效果..

就不贅述了直接給 sample code.


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; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); }

Result:

--

The bug existed in all possible states. Until I ran the code.

如果這篇文章有幫助到您幫我分享一下,讓我有寫下去的動力...