9

I am trying to save blob data (favicon) retrieved via AJAX, to localStorage.

Code :

var xhr = new XMLHttpRequest();
xhr.open('GET', 
'http://g.etfv.co/http://www.google.com',
true);
xhr.responseType = "blob";
xhr.onload = function(e){ //Stringify blob...
    localStorage['icon'] = JSON.stringify(xhr.response);
    //reload the icon from storage
    var fr = new FileReader();
    fr.onload = 
        function(e) {
            document.getElementById("myicon").src = fr.result;
        }
    fr.readAsDataURL(JSON.parse(localStorage['icon']));
    }
xhr.send(null);

The code is adapted from here with minor modifications to make it work with localStorage. localStorage saves all data as strings, so blobs need to be stringified somehow before being saved.

JSON doesn't deal with blobs as one of it's supported types, so it's no surprise that this code fails.

Is there any way to get the blob into localStorage?

Community
  • 1
  • 1
MadeOfAir
  • 2,339
  • 3
  • 25
  • 33

1 Answers1

12

Just store the blob as a data uri in local storage

var xhr = new XMLHttpRequest();
xhr.open('GET', 
'http://g.etfv.co/http://www.google.com',
true);
xhr.responseType = "blob";
xhr.onload = function(e){ //Stringify blob...
    //reload the icon from storage
    var fr = new FileReader();
    fr.onload = 
        function(e) {
            localStorage['icon'] = e.target.result;
            document.getElementById("myicon").src = localStorage['icon'];
        }
    fr.readAsDataURL(xhr.response);
}
xhr.send(null);
Musa
  • 89,286
  • 16
  • 105
  • 123
  • Well, at least this is inefficient. Try to compare `xhr.response.size()` with `e.target.result.length`. But I may resort to that in the end. – MadeOfAir Jan 09 '14 at 01:14
  • 3
    Its just over 33% larger (base64 encoding), but this is the only way I know of to convert the blob into a usable string. Maybe if you find a better way you can post it as an answer. – Musa Jan 09 '14 at 01:24
  • If I am going to store favicons they are going to be many, plus other data, so all the favicons can take 1mb from the available 5mb – MadeOfAir Jan 09 '14 at 06:30