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?
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.
To get items from localStorage, use the getItem() method. getItem() allows you to access the data stored in the browser's localStorage object.
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.
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.
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]));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With