javascript - 列出页面上所有图像的文件大小(Chrome 扩展)

标签 javascript ajax google-chrome google-chrome-extension

我想编写一个 Chrome 扩展程序,您可以在其中输入页面 URL,它会列出出现在该页面上的所有图像文件名以及这些图像的文件大小,例如“页面包含图像:1.jpg (65KB)、2.png (135KB)”。如何才能做到这一点?我也想避免将其作为 devtools 扩展。

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

最佳答案

您可以调用document.imagesdocument 中获取图像, 使用 fetch() , Response.blob()返回 Blob图像响应,检查.sizeBlob , 使用 URL() 获取图像名称构造函数

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

关于javascript - 列出页面上所有图像的文件大小(Chrome 扩展),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41085017/

相关文章:

sql - SSRS - 日期参数在 WebKit 浏览器中不显示日历控件

javascript - JavaScript 中类似函数的类

javascript - 原型(prototype)继承的构造函数分配

javascript - $.ajax调用node js等效吗?

javascript - 为什么我的 Javascript Chrome 扩展代码不起作用? (循环检查按钮)

javascript - 安全覆盖 Google Chrome 扩展中的 document.cookie

javascript - Node.js 示例无法在 Windows 10 上运行

javascript - 正则表达式字符串替换,同时保留原始换行符

javascript - Qlikview - 在选项卡/qvw 文档中滚动时卡住对象的位置

ajax - 如何在 Selenium IDE 中等待所有 ajax 请求完成?