简体   繁体   English

如何在仍然能够下载其内容的同时阻止元素跳转到新页面?

[英]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=')

If you run this code in a new tab it will only jump to that page.如果您在新选项卡中运行此代码,它只会跳转到该页面。 It only works if you run the code with the image already open.仅当您在已打开图像的情况下运行代码时,它才有效。 How can I stop the link.click() from jumping to the link while still having the image be downloaded?如何在仍然下载图像的同时阻止link.click()跳转到链接? (I know this wouldn't work if it was from a different domain because of CORS). (我知道如果它来自不同的域,因为 CORS,这是行不通的)。

Anchor element docs says " download only works for same-origin URLs, or the blob: and data: schemes ".锚元素文档说“下载仅适用于同源 URL,或 blob: 和 data: 方案”。

So if CORS allow it, you can fetch the resource, create the URI from the blob and then download it:因此,如果 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM