12

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.

3
  • 3
    You can't read from / write to the local file system with JavaScript. Commented Jun 17, 2014 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. Commented Jun 17, 2014 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. Commented Jun 18, 2014 at 7:59

4 Answers 4

27

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:

javascript
function getLocalStorage() { return JSON.stringify(localStorage) } function writeLocalStorage(data) { Object.keys(data).forEach(function(key) { localStorage.setItem(key, data[key])}) }
Sign up to request clarification or add additional context in comments.

1 Comment

FYI, I am running into an issue with this version because my localStorage contains stringified values that include escaped double-quotes and when they get stringified again, the resulting string is unable to be parsed with JSON.parse()
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.

javascript
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()

javascript
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.

Comments

7

This javascript below works for me:

javascript
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(); }

Comments

4

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

Put those two snippets in URLs accordingly

javascript
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
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.