I have an app in phonegap (pure js, html, css) where user signs in and then it has access to some aditional sites. My question is how to save his personal data or his session. There is no php involved for sending cookie or handling sessions. Everything need to be saved in JS (jQuery). How can I do this?
2 Answers
You can use HTML5 feature Local Storage
For eg;
When user logs in, set one variable as isAuthenticated in your local storage
By default, it will be 0, on successful login, set it to 1.
localStorage.isAuthenticated = 0; // default
OR
localStorage.setItem('isAuthenticated',0);
On Successful login
localStorage.isAuthenticated = 1; // default
OR
localStorage.setItem('isAuthenticated',1);
And whenever you want to check user's authenticity, simply compare value of isAuthenticated variable from Local Storage.
var isLoggedIn = localStorage.getItem('isAuthenticated');
if(isLoggedIn){
//your code
} else {
// invalid user code
}
UPDATE If you are storing javascript objects then
var myObject = { 'one': 1, 'two': 2, 'three': 3 };
// Put the object into storage
localStorage.setItem('myObject', JSON.stringify(myObject));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('myObject');
retrievedObject = JSON.parse(retrievedObject)
Convert your object into string using JSON.stringify and then store it into the local storage.
While retrieving cast that string back into the javascript object using JSON.parse
Looking at the local storage documentation, the functionality seems to be limited to handle only string key/value pairs.
You can take a look at the documentation here
PS : Phonegap has nothing to do with working of local storage or any other HTML feature. Phonegap is just a middleware that facilitates communication between your device hardware and your javascript/html code.
3 Comments
Here's the PhoneGap documentation on LocalStorage and SQL Database:
http://docs.phonegap.com/en/2.0.0/cordova_storage_storage.md.html#localStorage