Search code examples
javascriptimagegoogle-chrome-extensiongoogle-chrome-storagechrome-sync

putting an image into chrome.storage extension


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


Solution

  • 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.