Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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('sampledata');
data.push({sample: 'object'});
localStorage.setItem('varname',data);

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?

like image 226
Zim84 Avatar asked Nov 11 '12 22:11

Zim84


People also ask

Does localStorage expire on refresh?

LocalStorage has no expiration time, Data in the LocalStorage persist till the user manually delete it. This is the only difference between LocalStorage and SessionStorage.

How do I get specific data from local storage?

To get items from localStorage, use the getItem() method. getItem() allows you to access the data stored in the browser's localStorage object.

Does localStorage persist after restart?

The main features of localStorage are: Shared between all tabs and windows from the same origin. The data does not expire. It remains after the browser restart and even OS reboot.

Is it okay to store data in localStorage?

On the downside, localStorage is potentially vulnerable to cross-site scripting (XSS) attacks. If an attacker can inject malicious JavaScript into a webpage, they can steal an access token in localStorage. Also, unlike cookies, localStorage doesn't provide secure attributes that you can set to block attacks.


1 Answers

Here's how to import/export your entire localStorage

Export

copy(JSON.stringify(localStorage));

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

Import

var data = JSON.parse(/*paste stringified JSON from clipboard*/);
Object.keys(data).forEach(function (k) {
  localStorage.setItem(k, JSON.stringify(data[k]));
});
like image 193
Jeremy Bernier Avatar answered Oct 12 '22 16:10

Jeremy Bernier