Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

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

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 contains images: 1.jpg (65KB), 2.png (135KB)". How can this be done? I want to avoid making this a devtools extension as well.

I've tried using the webRequest API but I can see no way to access the body of the requests. The image size might be sent in the response header but this isn't guaranteed. I've tried using AJAX to grab the image data but the image data you get is the uncompressed version and this wouldn't be an accurate reflection of the actual file size.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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))
<img src="https://placehold.it/10x10">
<img src="https://placehold.it/20x20">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...