Thursday, June 6, 2024
 Popular · Latest · Hot · Upcoming
91
rated 0 times [  97] [ 6]  / answers: 1 / hits: 24341  / 11 Years ago, wed, january 8, 2014, 12:00:00

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?


More From » json

 Answers
5

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);

[#73300] Tuesday, January 7, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
samir

Total Points: 145
Total Questions: 90
Total Answers: 89

Location: Tokelau
Member since Sun, May 7, 2023
1 Year ago
;