我正在创建一个 Google-Chrome 扩展程序,我希望能够提取网站正在加载的一些图像并将它们放入扩展程序中。在某些情况下,这可能会导致对服务器的大量请求,从而有效地减慢它的速度。这些图像在用户访问页面时加载,因此扩展程序无需再次请求图像。有没有办法在不再次从服务器拉数据的情况下获取数据?
1 回答
Using binary Ajax, you can pull the images as Blob
objects, which FileReader
can convert to a base64 URL string.
Fetch the binary data of the image as an
ArrayBuffer
and store it in aBlob
:var oReq = new XMLHttpRequest(); oReq.open("GET", "/myfile.png", true); oReq.responseType = "arraybuffer"; oReq.onload = function(oEvent) { var blob = new Blob([oReq.response], {type: "image/png"}); // step 2 goes here... }; oReq.send();
(According to the spec, you can also do
oReq.responseType = "blob"
to makeoReq.response
aBlob
immediately, instead of anArrayBuffer
. I'm not 100% sure if this is actually supported yet.)Read the
Blob
withFileReader
:var fr = new FileReader(); fr.onload = function(e) { var dataUrl = e.target.result; // step 3 goes here... } fr.readAsDataURL(blob);
Finally, you have the URL stored in
dataUrl
. Assign it directly to thesrc
attribute of an image element:document.getElementById("myimg").src = dataUrl;
To avoid performing the fetch in the future, store the data URL in
localStorage
or an IndexedDB store.