0

I'm currently writing a Chrome extension that needs to save some images into chrome.storage memory. I'm currently making an array of objects:

var AnImage = new Image()
AnImage.src = http://image.image/imageurl.png
var ObjectToSave = {   ...,
    graph_img : AnImage,
     ... }
...
AnArray[x] = ObjectToSave

I output with a simple append

document.getElementById("AnElement").appendChild(ObjectToSave.graph_img)

But when I load it from storage and try to append it again, it returns an error

Error in response to storage.get: TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.

When I output it through console.log() it evaluates what has been retrieved as an object, but not anything I can recognise. I'm currently using chrome.storage.sync

Is there a way of doing this? There seems to be little help in the way of storing images, and of what exists is old and talks about encoding with base64 for the older storage API. But when I did my initial research there were people claiming that base64 encoding was no longer necessary

Jason
  • 779
  • 1
  • 9
  • 30
  • just save the url instead. `chrome.storage.sync.get`ting your image object will return an unusable object of type object. – Marc Guiselin Aug 07 '16 at 01:55
  • As per the documentation, chrome.storage is only for JSON-serializable stuff. Image is not, of course. – wOxxOm Aug 07 '16 at 05:13

2 Answers2

3

After more looking, I found out about the FileReader object that provides a more elegant way over using the canvas method. And as this is chrome specific compatibility is ensured.

function ImageLoader( url ){
    var imgxhr = new XMLHttpRequest();
        imgxhr.open( "GET", url + "?" + new Date().getTime() );
        imgxhr.responseType = "blob";
        imgxhr.onload = function (){
            if ( imgxhr.status===200 ){
                reader.readAsDataURL(imgxhr.response);
            }
        };
    var reader = new FileReader();
        reader.onloadend = function () {
            document.getElementById( "image" ).src = reader.result;
            chrome.storage.local.set( { Image : reader.result } );
        };
    imgxhr.send();
}

Using chrome.storage.local is needed as it is highly likely that the storage size limit for chrome.storage.sync will be exceeded.

Jason
  • 779
  • 1
  • 9
  • 30
  • Does this method provide the same binary data as, say, classical loading of the image URL to the `img`'s `src`attribute and then downloading it? In other words, is the content the "original" one or it's re-encoded? – Yin Cognyto Dec 20 '17 at 15:50
0

As Marc Guiselin and wOxxOm mentioned in the comments, chrome.storage will serialize the data first, to save image, you could:

  1. Save the image src. chrome.storage.sync.set({ src: img.src });
  2. Save the image dataURL.
Community
  • 1
  • 1
Haibara Ai
  • 10,703
  • 2
  • 31
  • 47