4

I am trying to save a DOM node to posterior insert it in another page of same website.

I am using jQuery with my extension. What I did in content_script.js was:

var variableToStore = localStorage["variableToStore"];

if (variableToStore == null) {
    localStorage["variableToStore"] = jQuery("#myDomNode").clone();
    variableToStore = localStorage["variableToStore"];
}

variableToStore.insertAfter(jQuery("#someelementofanotherpage"));

What I am doing wrong? localStorage cannot save DOM objects? If not, how can I achieve my objective?

Thanks.

Jack Andrews
  • 51
  • 1
  • 4

3 Answers3

3

Simply put, no you cannot store DOM elements in local storage. Even with jStorage plugin, you cannot store DOM elements in local storage as stated in the intro text: http://www.jstorage.info/

You can store an HTML-encoded string for JavaScript in local storage, then convert it back to html after (refer to this Q&A for help in that area)

Community
  • 1
  • 1
BumbleB2na
  • 10,723
  • 6
  • 28
  • 30
1

You may save a string with the html code instead, try this:

var div=$('<div></div>');
$("#myDomNode").clone().appendTo(div);
localStorage["variableToStore"] = escape(div.html());
...
var variableToStore = unescape(localStorage["variableToStore"]);
$(variableToStore).appendTo($("#someelementofanotherpage"));
Francois
  • 2,005
  • 21
  • 39
  • Thanks for the tips, @Francois. Your idea of include the desired html inside the div to correctly retrieve the full html was excellent. I just had to encode the html to storage works. I used the "escape()" function of javascrip to store properly, and "unescape()" after read it. – Jack Andrews Jun 12 '12 at 18:19
1

Francois' solution works, however clone() doesn't reflect JQuery modifications, so I had to run this before:

$("input").each(function(){
    $(this).attr("value", $(this).val());
});

I use overall for storing state of form with jStorage.

(I don't have enough reputation to comment, sorry)

  • Not having enough reputation to comment is not, in general, a reason to answer instead; but in your case it works as an answer. – Xan Jun 10 '14 at 05:52