Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save data to local storage

I'm trying to set a bush of variables in local storage but the function doesn't run, I've tried to get the value but without luck, How can I save fields in Local storage?

function setPerson(){ var person = { 'name': getElementById('name'), 'photo': getElementById('photo')};  // Put the object into the storage     alert(person);     localStorage.setItem('person', JSON.stringify(person)); }; 

HTML In the HTML I'm from fields put values into tags and they are populated, but when I try to fetch them and save them nothing is happening...

I also tried to out fixed values in there and then the alert is displayed, but then it only says object and not the value

var testObject = { 'one': 1, 'two': 2, 'three': 3 };  // Put the object into storage localStorage.setItem('testObject', JSON.stringify(testObject));  // Retrieve the object from storage var retrievedObject = localStorage.getItem('testObject'); alert('retrievedObject: ', JSON.parse(retrievedObject));; 
like image 855
user3637210 Avatar asked May 19 '14 17:05

user3637210


People also ask

Is it safe to save data in local storage?

No. localStorage is accessible by any webpage, and if you have the key, you can change whatever data you want. That being said, if you can devise a way to safely encrypt the keys, it doesn't matter how you transfer the data, if you can contain the data within a closure, then the data is (somewhat) safe.

How is data stored in localStorage?

LocalStorage is a datastore available in browsers. Data is stored as key/value pairs of strings, and each domain has access to its LocalStorage. When storing JavaScript objects, be sure to correctly convert them to a string with JSON. stringify() before saving.

How long data save in local storage?

localStorage - stores data with no expiration date. window. sessionStorage - stores data for one session (data is lost when the browser tab is closed)

Is local storage a good idea?

Local storage provides at least 5MB of data storage across all major web browsers, which is a heck of a lot more than the 4KB (maximum size) that you can store in a cookie. This makes local storage particularly useful if you want to cache some application data in the browser for later usage.


1 Answers

You can use localStorage like this:

// Retrieve your data from locaStorage var saveData = JSON.parse(localStorage.saveData || null) || {};  // Store your data. function saveStuff(obj) {   saveData.obj = obj;   // saveData.foo = foo;   saveData.time = new Date().getTime();   localStorage.saveData = JSON.stringify(saveData); }  // Do something with your data. function loadStuff() {   return saveData.obj || "default"; } 

jsFiddle

like image 115
Jonathan Avatar answered Sep 18 '22 13:09

Jonathan