How to store a complete div in localstorage

后端 未结 1 1151
执笔经年
执笔经年 2021-01-13 20:31

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

相关标签:
1条回答
  • 2021-01-13 20:36

    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) {
    }
    
    0 讨论(0)
提交回复
热议问题