我正在创建一个 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
ArrayBufferand 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.responseaBlobimmediately, instead of anArrayBuffer. I'm not 100% sure if this is actually supported yet.)Read the
BlobwithFileReader: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 thesrcattribute of an image element:document.getElementById("myimg").src = dataUrl;To avoid performing the fetch in the future, store the data URL in
localStorageor an IndexedDB store.