Save HTML locally with Javascript

后端 未结 10 1545
夕颜
夕颜 2020-12-03 01:19

I do know that Javascript cannot write data in the filesystem, for security reasons. I have often read that the only way to save data locally with Javascript is cookies or <

10条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-03 01:51

    Yes, it's possible.

    In your example, you are already using ContentEditable and most of tutorials for that attribute have some sort of localStrorage example, ie. http://www.html5tuts.co.uk/demos/localstorage/

    On page load, script should check localStorage for data and if true, populate element. Any changes in content could be saved in localStorage when clicking save button (or automatically, in linked example, using blur and focus). Additionally you can use this snippet to check weather user is online or offline and based on state modify your logic:

    // check if online/offline
    // http://www.kirupa.com/html5/check_if_internet_connection_exists_in_javascript.htm
    function doesConnectionExist() {
        var xhr = new XMLHttpRequest();
        var file = "http://www.yoursite.com/somefile.png";
        var randomNum = Math.round(Math.random() * 10000);
    
        xhr.open('HEAD', file + "?rand=" + randomNum, false);
    
        try {
            xhr.send();
    
            if (xhr.status >= 200 && xhr.status < 304) {
                return true;
            } else {
                return false;
            }
        } catch (e) {
            return false;
        }
    }
    

    EDIT: More advance version of localStorage is Mozilla localForage which allows storing other types of data besides strings.

提交回复
热议问题