I am creating a Google-Chrome extension and I want to be able to pull some images that a website is loading and put them in the extension. In some cases, this can result in a lot of requests to the server, effectively slowing it down. These images are loaded when the user visits the page, so there is no need for the extension to request the images again. Is there any way to get the data without pulling the data from the server again?
Asked
Active
Viewed 142 times
1
-
Doesn't the server send appropriate cache headers or what is your problem? – Bergi Jul 03 '13 at 18:26
-
It is not my server. I cannot change the cache headers. It doesn't look like they are using any. – Franz Payer Jul 03 '13 at 18:51
-
Then I guess you should try to overwrite/set them from your extension – Bergi Jul 03 '13 at 18:57
-
That would be what I'm trying to do... – Franz Payer Jul 03 '13 at 19:07
-
1@Bergi Setting Cache control headers from the extension has no influence on caching. – Rob W Jul 03 '13 at 19:43
-
@RobW: Thanks, didn't know that. Is there anything that lets you manipulate the cache from an extension then? – Bergi Jul 03 '13 at 20:43
-
There's no generic method, unfortunately. @FranzPayer Can you share more information on how the images are loaded/used? – Rob W Jul 03 '13 at 20:47
-
They are loaded via ajax requests. I am able to log the requests as they pass by and then make my own requests via ajax as well. – Franz Payer Jul 03 '13 at 21:03
1 Answers
0
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.

apsillers
- 112,806
- 17
- 235
- 239
-
Doesn't quite solve the problem, my extension still has to load the images. The problem was that the original webpage (not my code) loads the page. Then, after the page is loaded, my extension wants to get the cached version of the resources. Your code would only be helpful if my extension had to load the resources multiple times from the extension. – Franz Payer Jul 03 '13 at 20:04