透過 document.execCommand('SaveAs') 可在瀏覽器中觸發「另存新檔」對話框,讓使用者將目前頁面或指定頁面存為本地檔案。以下提供兩種常見情境的實作方式。
index.html(下載觸發頁)
<a href="#" onclick="window.open('temp.html'); return false;">下載檔案</a>
temp.html(被下載的目標頁)
<script language="javascript">
if (typeof(window.opener) != "undefined") {
document.execCommand('SaveAs');
window.close();
}
</script>
說明:
1. 主頁面開啟 temp.html 於新視窗。
2. temp.html 偵測到有 opener(即被 window.open 開啟),才執行 SaveAs 並自動關閉視窗。
3. 若直接開啟 temp.html,不會彈出存檔對話框,避免干擾正常瀏覽。
<button onclick="javascript:document.execCommand('SaveAs');">儲存本頁面</button>
點擊按鈕即彈出「另存新檔」對話框,讓使用者將目前頁面存為 .html 或 .htm。
document.execCommand('SaveAs') 為 IE 專有功能,現代瀏覽器(Chrome、Firefox、Edge)已不支援或行為不一致。<a href="檔案路徑" download="檔名.html">(HTML5 download 屬性)或伺服器端設定 Content-Disposition: attachment 標頭。