瀏覽器安全策略限制直接下載跨域圖片,傳統<a download>屬性受同源策略限制。本文介紹一種利用隱藏iframe載入圖片並調用document.execCommand('SaveAs')的兼容方案,適用於同域圖片下載場景。
<a href="picName.jpg" id="pic1" onclick="savepic(); return false;" style="cursor:pointer">點擊下載</a>
<script>
function savepic() {
var imageName = document.getElementById('pic1');
var iframeName = 'downloadIframe';
// 檢查iframe是否已創建
if (window.frames[iframeName] === undefined) {
var iframe = document.createElement('IFRAME');
iframe.name = iframeName;
iframe.style.display = 'none';
document.body.appendChild(iframe);
// 短暫延遲等待iframe就緒
setTimeout(savepic, 1);
return;
}
// 在iframe中打開圖片並執行保存
var picWin = window.open(imageName.href, iframeName);
if (picWin) {
try {
picWin.document.execCommand('SaveAs');
} catch (e) {
console.warn('SaveAs不支援或被阻止', e);
}
}
// 清理iframe
var iframeEl = document.getElementsByName(iframeName)[0];
if (iframeEl) iframeEl.parentNode.removeChild(iframeEl);
}
</script>
return false阻止鏈接默認跳轉iframe作為下載容器window.open(url, iframeName)在指定iframe中加載圖片execCommand('SaveAs')喚起瀏覽器「另存為」對話框(IE/舊Edge支援較好)| 方案 | 支援場景 | 跨域 | 備註 |
|---|---|---|---|
<a download href="..."> | 同域、Blob、DataURL | ❌ 受CORS限制 | HTML5標準,首選 |
| Blob + ObjectURL | 任意二進制、Canvas導出 | ✅ 可fetch跨域後轉Blob | 現代通用方案 |
| iframe + execCommand | 同域圖片 | ❌ | 老項目兼容,逐漸棄用 |
| Service Worker 攔截 | 離線、緩存、背景下載 | ✅ 可控 | PWA進階用法 |
async function downloadImage(url, filename) {
try {
const response = await fetch(url, { mode: 'cors', credentials: 'omit' });
const blob = await response.blob();
const blobUrl = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = blobUrl;
a.download = filename || 'image.png';
a.style.display = 'none';
document.body.appendChild(a);
a.click();
setTimeout(() => {
document.body.removeChild(a);
URL.revokeObjectURL(blobUrl);
}, 100);
} catch (e) {
console.error('下載失敗', e);
// 降級:新窗口打開
window.open(url, '_blank');
}
}
execCommand('SaveAs')已從標準移除,Chrome 80+、Firefox 74+ 不再支援Access-Control-Allow-Origin或代理下載streams或File System Access API避免內存峰值download屬性行為不一,建議引導用戶長按保存