List file sizes of all images on a page (Chrome Extension)

前端 未结 1 1232
你的背包
你的背包 2020-12-04 01:09

I want to write a Chrome Extension where you enter a page URL and it lists all the image filenames that appear on that page with the file sizes of those images e.g. \"Page c

1条回答
  •  伪装坚强ぢ
    2020-12-04 01:39

    You can call document.images to get images in document, use fetch(), Response.blob() to return Blob response of image, check .size of Blob, get name of image with URL() constructor

    let getImages = () => {
      let images = Array.from(document.images);
      return Promise.all(images.map(img => fetch(img.src)
        .then(response => response.blob())))
        .then(blobs => {
          return blobs.map((img, index) => {
            let name = new URL(images[index].src).pathname.split("/").pop();
            name = !/\./.test(name) 
                   ? name + "." + img.type.replace(/.+\/|;.+/g, "") 
                   : name;
            return {
              name: name,
              size: img.size
            }
          });
        })
    }
    
    getImages()
    .then(images => console.log(JSON.stringify(images)))
    .catch(e => console.log(e))
    
    

    0 讨论(0)
提交回复
热议问题