I\'m trying to create a basic text annotator. I would like to save the annotated text (a complete div) with all the tags inside in local storage. My approach is pretty nai
It doesn't work because JSON.stringify
isn't the correct way to serialize a div. JSON.stringify
only includes the object's "own" properties, but the properties you care about on a div
(primarily innerHTML
or outerHTML
) are inherited, not "own".
Instead, you probably want to save outerHTML
:
localStorage.setItem(key, annotatedtext.outerHTML);
...or possibly innerHTML
.
Side note: Your check for whether the browser has localStorage
is incorrect. if (localStorage)
will throw an error if localStorage
is completely undeclared (as it will be in a browser without local storage). You probably wanted if (typeof localStorage !== "undefined")
, which won't throw, but will be true if localStorage
is completely undeclared.
But even that check isn't thorough enough to handle whether you can use local storage, because of the somewhat odd ways private browsing works on some browsers. To know whether you can use local storage:
var canUseStorage = false;
try {
var key = "test" + Date.now() + Math.random();
localStorage.setItem(key, key);
if (localStorage.getItem(key) == key) {
canUseStorage = true;
localStorage.removeItem(key);
}
}
catch (e) {
}