11

Is there a way to easily save and restore the local storage to a file in jquery or JavaScript?

There are 3 scenarios for this:

  1. testing with a specific local storage

  2. making a backup of the local storage in some specific situations where this data is critical (we want to save in case local cache is deleted)

  3. Setting up another browser from an existing local storage.

shelbypereira
  • 2,097
  • 3
  • 27
  • 50
  • 3
    You can't read from / write to the local file system with JavaScript. – Cerbrus Jun 17 '14 at 12:23
  • 3
    The above isn't true anymore with the File APIs in newest JavaScript. But much simpler, your solution could be a simple JS file per data set that flushes and repopulates the storage with "hard coded" data that sits in the same file, e.g. as JS objects. – marekful Jun 17 '14 at 12:25
  • Marcell: your suggestion would work for testing (case 1 above), but not for 2, where I need to save the local storage for a specific production situation. Also, it looks like Fiel APIS is supported on Chrome and explorer current versions. – shelbypereira Jun 18 '14 at 07:59

4 Answers4

22

I probably would have just tacked this on as a comment to Nathaniel Johnson's answer, but I don't have the reputation yet! With regard with those methods, here are some more simple versions of his functions:

function getLocalStorage() {
    return JSON.stringify(localStorage)
}

function writeLocalStorage(data) {
    Object.keys(data).forEach(function(key) { localStorage.setItem(key, data[key])})
}
Alistair Jones
  • 553
  • 4
  • 10
9

The process for saving and retrieving local storage has two parts.

First you must be able to retrieve the contents of local storage in a form that is manageable in javascript. Since local storage is a map of key-value pairs the easiest way to this is to turn local storage into a javascript object. Then take this object and turn it into a JSON string. What you do with this string is up to you but I find it easiest to just have the user copy the string into an email.

function getLocalStorage() {
    var a = {};
    for (var i = 0; i < localStorage.length; i++) {
        var k = localStorage.key(i);
        var v = localStorage.getItem(k);
        a[k] = v;
    }
    var s = JSON.stringify(a);
    return s;
}

When I get the string, I use the following function to turn my local storage into a copy of their local storage. Remember to wipe your local storage clean before duplicating their data with a call to localStorage.clear()

function writeLocalStorage(data) {
    var o = JSON.parse(data);
    for (var property in o) {
        if (o.hasOwnProperty(property)) {
            localStorage.setItem(property, o[property]);
        }
    }
}

The last part of your question is how to protect the data from overwriting. You can't write to a local file, however, you can have copy the data into <textarea> and tell the user how to copy and paste the data into a email or a more direct approach.

Community
  • 1
  • 1
Nathaniel Johnson
  • 4,731
  • 1
  • 42
  • 69
4

This javascript below works for me:

function getLocalstorageToFile(fileName) {
  
  /* dump local storage to string */
  
  var a = {};
  for (var i = 0; i < localStorage.length; i++) {
    var k = localStorage.key(i);
    var v = localStorage.getItem(k);
    a[k] = v;
  }
  
  /* save as blob */
  
  var textToSave = JSON.stringify(a)
  var textToSaveAsBlob = new Blob([textToSave], {
    type: "text/plain"
  });
  var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
  
  /* download without button hack */
  
  var downloadLink = document.createElement("a");
  downloadLink.download = fileName;
  downloadLink.innerHTML = "Download File";
  downloadLink.href = textToSaveAsURL;
  downloadLink.onclick = function () {
    document.body.removeChild(event.target);
  };
  downloadLink.style.display = "none";
  document.body.appendChild(downloadLink);
  downloadLink.click();
  
}
user2401543
  • 1,059
  • 11
  • 19
2

Create two bookmarks in Chrome with names e.g. LS BACKUP and LS RESTORE

Put those two snippets in URLs accordingly

javascript:!function(e){var o=document.createElement("textarea"),t=document.getSelection();o.textContent=e,document.body.appendChild(o),t.removeAllRanges(),o.select(),document.execCommand("copy"),t.removeAllRanges(),document.body.removeChild(o)}(JSON.stringify(localStorage)),alert("Local storage is copied to clipboard");
javascript:!function(){let t=prompt("Input local storage backup string");try{t=JSON.parse(t),Object.keys(t).forEach(r=>{try{localStorage.setItem(r,t[r])}catch(a){alert(`Error occurred with the key "${r}" and value "${t[r]}"`)}})}catch(t){alert("Input is not a valid JSON string")}}();

The first one will copy a JSON string to clipboard.

The second one will prompt you to insert a JSON string, which will be parsed and put to local storage.

enter image description here

Sergiy Seletskyy
  • 16,236
  • 7
  • 69
  • 80