我想编写一个 Chrome 扩展程序,您可以在其中输入页面 URL,它会列出出现在该页面上的所有图像文件名以及这些图像的文件大小,例如“页面包含图像:1.jpg (65KB)、2.png (135KB)”。如何才能做到这一点?我也想避免将其作为 devtools 扩展。
我试过使用 webRequest API,但我看不到访问请求正文的方法。图像大小可能会在响应 header 中发送,但这不能保证。我试过使用 AJAX 获取图像数据,但您获得的图像数据是未压缩的版本,这不能准确反射(reflect)实际文件大小。
最佳答案
您可以调用document.images
在 document
中获取图像, 使用 fetch()
, Response.blob()
返回 Blob
图像响应,检查.size
的 Blob
, 使用 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/