1

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?

Franz Payer
  • 4,069
  • 15
  • 53
  • 77

1 Answers1

0

Using binary Ajax, you can pull the images as Blob objects, which FileReader can convert to a base64 URL string.

  1. Fetch the binary data of the image as an ArrayBuffer and store it in a Blob:

    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 make oReq.response a Blob immediately, instead of an ArrayBuffer. I'm not 100% sure if this is actually supported yet.)

  2. Read the Blob with FileReader:

    var fr = new FileReader();
    fr.onload = function(e) {
        var dataUrl = e.target.result;
        // step 3 goes here...
    }
    fr.readAsDataURL(blob);
    
  3. Finally, you have the URL stored in dataUrl. Assign it directly to the src 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