1

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.

apaderno
  • 28,547
  • 16
  • 75
  • 90
gdanko
  • 1,922
  • 4
  • 20
  • 31

1 Answers1

1

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.

Community
  • 1
  • 1
robertc
  • 74,533
  • 18
  • 193
  • 177
  • Well, I see JSON.stringify and it looks like the direction I am going in. Is there such a beast for regular old XML? – gdanko Feb 03 '11 at 21:11
  • var string = (new XMLSerializer()).serializeToString(data); – gdanko Feb 03 '11 at 21:51
  • @user589254 XML parsing is one of those things [that works very differently in IE compared to most other browsers](http://www.mikechambers.com/blog/2006/01/09/parsing-xml-in-javascript/), you might want to investigate some of the lightweight AJAX libraries. – robertc Feb 03 '11 at 23:39