auto download with js

February 1, 2024

© 2024 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui(2024-02-01 21:43:26 +0000). auto download with js. https://borui/blog/2024-02-01-en-auto-download-with-js.
@misc{
  borui2024,
  author = {borui},
  title = {auto download with js},
  year = {2024},
  publisher = {borui's blog},
  journal = {borui's blog},
  url={https://borui/blog/2024-02-01-en-auto-download-with-js}
}

Most common method: simulate click on anchor element

function downloadFile(url, fname) {
    //create anchor and click it
    let a = document.createElement("a");
    //set resource url
    a.href = url;
    //set download default filename 
    a.download = `${fname}.png`;
    a.click();
}

Downdloading from crossorigin Issues

Description of issue: When trying to download an image from an url on click, it just redirects to that url instead of downloading.

Answer to this phenomenon:

The problem is because you're using a cross-domain URL. From the documentation for the download attribute:

download only works for same-origin URLs, or the blob: and data: schemes.

To fix this you need to host the image on the same domain as the parent site.

  1. Rory McCrossan. [@Rory McCrossan]. (March 4, 2020). The problem is because you're using a cross-domain URL. From the documentation for the download attribute: download only works for same-origin URLs, or the blob: and data: schemes. [Answer]. stackoverflow. https://stackoverflow.com/questions/60522840/html-download-attribute-redirects-to-url-instead-of-downloading/60522885#60522885

📓 Note: download only works for same-origin URLs, or the blob: and data: schemes.

  1. <a>: The Anchor element. (n.d.). MDN docs. Retrieved Jan 30, 2024, from https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#download

How to handle cross domain

we can fetch the files then create an url for download

// imgsrc or chang it to url for any resources you want
fetch(img.src)
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.blob();
    })
    .then(blob => {
        //create obj url from blob
        let objurl = URL.createObjectURL(blob);
        //create anchor and click it
        let a = document.createElement("a");
        a.href = objurl;
        a.download = `${fname}.png`;
        a.click();
    })
    .catch(error => {
        console.error('Error fetching image:', error);
    });

anti-hotlinking

When the project references a remote image fixed link (mostly a third-party link), the image will not be displayed on the page and an error 403 will be reported. It should be that anti-hotlinking is added and access to the image will be detected referer; however, if you open the remote link alone, you can open it again.

anti_hotlinking0alt

The main reason is that the site's pictures adopt anti-hotlinking rules. When the site learns that there is a request, it will first determine the information in the request header. If so there are Referer in request headers, the server will then determine whether the Referer header information meets the requirements according to its own rules. The Referer information is Request the source address of this image.

There is a field in the header of the http request body referrer, which is used to indicate the source address information of the http request. This referrer information can be omitted but cannot be modified. That is to say, you can only set whether to include this referrer information, and you cannot customize the referrer information value.

After getting the referrer value, the server can perform related processing, such as picture resources. You can use the referrer value to determine whether the request comes from this site. If not, it will return 403 or redirect to return other information, thereby preventing hotlinking of pictures. The reason why 403 appears above is because the request was for resources on someone else's server, but request was sent with my own referrer information there and was intercepted by the other party's server and returned 403. anti_hotlinking2alt

anti_hotlinking3alt

The referrer policy (source policy) can be set through meta on the front end, so the solution to the above 403 situation is to set the referrer so no-referrer that the request will not carry the referrer information, and the other server will not be able to intercept it. anti_hotlinking1alt

  1. 铁锤妹妹@. (26 Oct, 2021.). 关于图片防盗链 - 图片加载报错403,但可以单独打开图片链接. CSDN. [Blog post]. Retrieved Jan 30, 2024, from https://blog.csdn.net/weixin_45811256/article/details/120977309

Multi-file download

use a for loop to create and click anchor link iteratively

zipping

Use JSZip library: https://github.com/Stuk/jszip

Tainted Canvas Issue for cross origin image

Addtional Reading:

  1. 无知的小菜鸡. (16 April, 2023.). 浏览器插件官方demo学习(四):图片下载(chrome image download extension implementation). CSDN. [Blog post]. Retrieved Jan 30, 2024, from https://blog.csdn.net/weixin_41897680/article/details/129801109
  2. chrome-extensions-samples. branch main. commit b5e3683. https://github.com/GoogleChrome/chrome-extensions-samples/tree/main/_archive/mv2/extensions/download_images