1

我正在创建一个 Google-Chrome 扩展程序,我希望能够提取网站正在加载的一些图像并将它们放入扩展程序中。在某些情况下,这可能会导致对服务器的大量请求,从而有效地减慢它的速度。这些图像在用户访问页面时加载,因此扩展程序无需再次请求图像。有没有办法在不再次从服务器拉数据的情况下获取数据?

4

1 回答 1

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.

于 2013-07-03T19:55:52.333 回答