export Data in localStorage for later re-import

I want to export a few items from my localStorage to save it externally but in a format so that I can import it again later.

My attempt was to write executable code that can be pasted later in a textarea. Then the value of that textare will simply be eval()ed.

Problem: The data stored in localStorage were stored as

var data = [];
data.push({sample: 'object'});

So it contains various chars I don’t like, like ‘, ” etc

My (not working) solution so far was:

var container = $('#localDataContainer');
container.append('localStorage.setItem("cockpitLastVisited","' + localStorage.getItem("cockpitLastVisited") + '");<br/>');
container.append('localStorage.setItem("cockpit_services","' + localStorage.getItem("cockpit_services") + '");<br/>');
container.append('localStorage.setItem("cockpit_users","' + localStorage.getItem("cockpit_users") + '");');

If my attempt seems to be OK, what is the best way to create code that can then be executed the way it is?

Here’s how to import/export your entire localStorage



This will copy your localStorage to your clipboard. (You need two JSON.stringify()’s to get the quotes escaped.)


var data = JSON.parse(/*paste stringified JSON from clipboard*/);
Object.keys(data).forEach(function (k) {
  localStorage.setItem(k, JSON.stringify(data[k]));

Just an improved version of Jeremy. To simplify the process

copy('var data="+JSON.stringify(localStorage)+";Object.keys(data).forEach(function (k){localStorage.setItem(k, data[k]);});');

Run this in console where you need to export, it copies localstorage content along with code to clipboard and just paste it in the console where you want to import.

You can encode Objects into Strings using JSON.stringify (object to String) and decode Strings into Objects using JSON.parse (String to Object).

Write to localStorage


Read from localStorage

var originalVarname= JSON.parse(localStorage.getItem("varname"));




var data = JSON.parse(/*previously copied stringified JSON from clipboard*/);
Object.keys(data).forEach(function (k) {
  localStorage.setItem(k, data[k]);

Just a modernized version of @iceLord answer.

Read More:   Selenium Webdriver (node.js) take screenshot and save test results

Just run this in the console, it will put the code to restore the localStorage back into your clipboard.


Bookmarklet version

javascript:prompt(`localStorage from ${location.host}${new Date().toLocaleString()}`, `/* localStorage from ${location.host}${new Date().toLocaleString()}*/Object.entries(  ${JSON.stringify(localStorage)}).forEach(([k,v])=>localStorage.setItem(k,v))`)

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts