2

I want to store an XML document in sessionStorage. When I do this it seems to save ok as an XMLDocument. When I try to access it (on a page refresh) the object comes back as [object Object] as opposed to [object XMLDocument].

How do I get the data out of sessionStorage as an XMLDocument (or convert it to one?)

Chris
  • 26,744
  • 48
  • 193
  • 345

2 Answers2

4

You may want to serialize XMLDocument before saving it in storage:

var xml = new XMLSerializer().serializeToString(originalDom);
sessionStorage.setItem("myDocument", xml);

and then unserialize after loading data from storage:

var xml = sessionStorage.getItem("myDocument");
var restoredDom = new DOMParser().parseFromString(xml, "text/xml");
Sergey Ilinsky
  • 31,255
  • 9
  • 54
  • 56
  • But new XMLSerializer().serializeToString(originalDom); not completely converting childs into proper string. – Mahesh Jan 02 '20 at 19:08
2

localStorage and sessionStorage can only hold strings. Have a look at the interface definition:

interface Storage {
  readonly attribute unsigned long length;
  [IndexGetter] DOMString key(in unsigned long index);
  [NameGetter] DOMString getItem(in DOMString key);
  [NameSetter] void setItem(in DOMString key, in DOMString data);
  [NameDeleter] void removeItem(in DOMString key);
  void clear();
};

You cannot store objects unless you serialize them. So in your case, you have to serialize it to XML.

If you received the XML document as text, just store it directly. You can use jQuery.parseXML() to parse it after retrieval.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143