'save restore local storage to a local file
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:
testing with a specific local storage
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)
Setting up another browser from an existing local storage.
Solution 1:[1]
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])})
}
Solution 2:[2]
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();
}
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alistair Jones |
| Solution 2 | user2401543 |
| Solution 3 | Sergiy Seletskyy |

