[英]How to stop a element from jumping to new page while still being able to download its content?
function downloadStuff(theLink) {
var link = document.createElement('a');
link.href = theLink
link.download = 'Download';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
downloadStuff('https://media.istockphoto.com/photos/carrot-isolated-on-white-picture-id1157946850?k=6&m=1157946850&s=612x612&w=0&h=3dZtC10gyHO3CudANa8KF92WRBz1l1vq4LEoVjeOBEM=')
如果您在新選項卡中運行此代碼,它只會跳轉到該頁面。 僅當您在已打開圖像的情況下運行代碼時,它才有效。 如何在仍然下載圖像的同時阻止link.click()
跳轉到鏈接? (我知道如果它來自不同的域,因為 CORS,這是行不通的)。
錨元素文檔說“下載僅適用於同源 URL,或 blob: 和 data: 方案”。
因此,如果 CORS 允許,您可以獲取資源,從 blob 創建 URI,然后下載它:
async function downloadStuff(theLink) {
const result = await fetch(theLink);
const blob = await result.blob();
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'Download';
document.body.appendChild(link);
link.click();
link.remove();
}
downloadStuff('https://media.istockphoto.com/photos/carrot-isolated-on-white-picture-id1157946850?k=6&m=1157946850&s=612x612&w=0&h=3dZtC10gyHO3CudANa8KF92WRBz1l1vq4LEoVjeOBEM=');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.