Can XMLHttpRequest data be stored in localStorage?

2.6k Views Asked by At

I am writing a Safari extension that makes an XMLHttpRequest for some XML data using jQuery.ajax. If I do console.log(data) in the process data function, I get an item Document which I can traverse.

I want to store this ajax data in localStorage. So in the first few lines of the processDocument function I have this:

function processResponse(data) {
    localStorage.removeItem("myData");
    localStorage.setItem("myData", data);
    console.log('post-load: there are ' + localStorage.length + ' items in the local storage array.');
    console.log("post-load data: " + data);
    console.log("post-load myData: " + localStorage.myData);

The console.log will show me:
post-load: there are 1 items in the local storage array.
post-load data: [object Document]
post-load myData: [object Document]

So it looks like I have valid data here. But the messageHandler function when it responds to the button on the toolbar also polls the local storage like this:

console.log('There are ' + localStorage.length + ' items in the local storage array.');
for (var x = 0; x < localStorage.length; x++) {
    console.log(x + ": " + localStorage[x]);
}
if (localStorage.myData == undefined) {
    console.log("myData is undefined");
    doSomething();
} else {
    console.log("myData is defined");
    doSomethingElse();
}

The console log here will show:
There are 1 items in the local storage array.
0: undefined
myData is defined

Is there something I need to do in order to properly store this XML data in localStorage? Shouldn't localStorage preserve the integrity of this object? Perhaps I am missing something here.

1

There are 1 best solutions below

3
On

Despite what your initial debug output appears to be telling you, Local storage doesn't store objects it stores strings. To get XML back you should store it as a string and then parse the string back into XML when you retrieve it. This answer describes one approach, you may need to adapt it specifically for XML.