列出页面上所有图片的文件大小(Chrome扩展程序) [英] List file sizes of all images on a page (Chrome Extension)

查看:153
本文介绍了列出页面上所有图片的文件大小(Chrome扩展程序)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在您输入网页网址的地方编写Chrome扩展程序,并列出该网页上显示的所有图片文件名以及这些图片的文件大小,例如页面包含图像:1.jpg(65KB),2.png(135KB)。如何才能做到这一点?我希望避免将其作为devtools扩展。

我试过使用webRequest API,但是我看不到访问请求正文的方法。图像大小可能会在响应头中发送,但不能保证。我已经尝试使用AJAX来获取图像数据,但获取的图像数据是未压缩的版本,这不会是实际文件大小的准确反映。

解决方案

您可以调用 document.images c $ c>> document ,使用 fetch() Response.blob()返回 Blob 图片的响应,请检查 Blob .size ,使用 URL()构造函数获取图像名称

  let getImages =()=> {let images = Array.from(document.images);返回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()。然后(图像=> console.log(JSON.stringify(图像)))。catch(e => console.log(e)) 

 < img src =https://placehold.it/10x10>< img src =https:// placehold。 it / 20x20>  


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.

解决方案

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">

这篇关于列出页面上所有图片的文件大小(Chrome扩展程序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆