Jason Allan Jason Allan - 1 year ago 63
Javascript Question

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


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

Answer Source

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 ){
    var reader = new FileReader();
        reader.onloadend = function () {
            document.getElementById( "image" ).src = reader.result;
            chrome.storage.local.set( { Image : reader.result } );

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download