Store Javascript variable client side - javascript

Not duplicate : I've read many questions like this and it always ended up "use PHP or server-side stuff, and watch out for injection/data manipulation".
I want to store simple stuff on the client side (save and load), like a Google Map location, and want it to stay between refresh of the page.
I don't want to use PHP or any server-side thing.
How can I proceed ?
Thanks

You can use cookies or localStorage.

If html5 is not a problem I would say localstorage is the way to go:
//set value
localStorage.setItem('todoData', this.innerHTML);
//read value
if ( localStorage.getItem('todoData') ) {
edit.innerHTML = localStorage.getItem('todoData');
}
ripped from
http://net.tutsplus.com/tutorials/html-css-techniques/quick-tip-learning-about-html5-local-storage/ :-)

There are multiple options to store data in client side - IndexedDB, localstorage, webSQL, SessionStorage, Cookies, etc.
IndexedDB
Data can be queried efficiently. No limitation in size( but volume or
disk drivers limits the size )
It will store in Key-Object format
It will not be supported in safari browser
Support Queries
Asynchronous
localstorage
It will store value in key-value format (value should be always
String)
Synchronous
Helpful if you need to store a small amount of data
Limited size (Depends on browser)
Session Storage
If the user closes the tab, it will clear the data
You can check YDN-DB here

The key issue you have to keep in mind is you can't trust the client. If it's okay for the client to ask for any location, then it's okay for you to store the location on the client side. But you can't confirm that the value that you get back from the client side is one you have given to that client.
That's what it meant by "data manipulation" [injection is a special type of data manipulation, in that it is manipulated to include things like end quote marks if you're using it as part of a SQL query or other script.]

I highly suggest using localStorage for a few reasons:
It's supported by modern browsers,
INCLUDING IE.
You can store up to 5MB of data (10 in IE) where as a cookie is mere 4KBs
There's lots of libraries to make this easy. One of the most popular is LawnChair: http://westcoastlogic.com/lawnchair/ This will actually write to multiple places, including cookies, so that data isn't lost easily.
Also, as a note, you can't store objects with localStorage, just like you cant with cookies, however you can convert them. For example, if you want to store a Date() don't store it as new Date() store it as: '\'+Date().getTime()+'\'. Same for other objects.

Use Cookie.
How to access via javascript.

How about storing it in a cookie?
For JavaScript I recommend using jQuery, which simplifies a lot of work.
e.g. http://plugins.jquery.com/project/Cookie

Take a look at HTML5 Local Storage

Related

How to save progress in an html game

I want to know how I can save the progress a player has made in a game that I am making. Could I do this through cookies or how else can I save to the players computer? Thanks for all of the help!
You have pretty much two options for saving localy using Javascript, which are cookies and localStorage.
With Cookies:
The document.cookie property is used for setting, reading, altering and deleting browser cookies.
To set a cookie, document.cookie="cookiename=Foo Bar";, alternatively like so if you want an expiry date: document.cookie="cookiename=Foo Bar; expires=Mon, 18 Jan 2016 12:00:00 UTC";
To read a cookie, just the code document.cookie will return all of your site's cookies on that page. It doesn't put them in an array, but instead a single string in the format of cookiename=foobar; nextcookiename=foobar;, etc. You can turn this into an array easily using document.cookie.split("; ");
To alter a cookie, simply set it again as described above, as that will overwrite it
To delete a cookie, set it again with an expiry date in the past. This will overwrite it, and then it will expire, deleting it.
With localStorage:
The new HTML5 localStorage Object is another way to store data locally:
To set an item in localStorage, use localStorage.setItem('itemname','contents');
To read an item, it's localStorage.getItem('itemname');. You can check if an item exists using "truthy" values (i.e. if(localStorage.getItem('itemname')))
You can alter a localStorage item using localStorage.setItem as described above.
You can delete a localStorage item using localStorage.removeItem('itemname').
Which should I use?
Cookies are supported in just about any browser that you can think of, however they expire (they get deleted after a set amount of time) and also can be disabled by users. Personally, I also find document.cookie a clunky interface.
localStorage on the other hand cannot be easily disabled by the user, and provides a more accessible interface for the programmer. As far as I'm aware, there is no expiration for localStorage. Since localStorage is new with HTML5, it may not work in some older browsers (however it's got great coverage on new browsers, see http://caniuse.com/#feat=namevalue-storage). Note that there is a limit for storing data on your entire site, not just for one item.
In the end, it's up to you. Pick the one you think is going to work best for your game - if you're already using other HTML5 content (such as <canvas>) then there's no harm in localStorage and you'll be using a more reliable storage method. However, if you're happy with cookies then they are a perfectly viable option used by thousands of extremely popular sites - some even use both! One advantage to cookies is that they can be accessed by your web server, whereas localStorage cannot be.
Either way, you'll need to check out the cookie law, which effects all types of storage on the user's computers by a web app.
The hardest part of this problem is not finding a way to persist the data, but instead designing your game in such a way that you have a "game state" that can be serialized for saving between sessions.
Imagine you are writing a game with a player and a score and you're using two variables to represent them.
var player = { x: 4, y: 3 };
var score = 10;
It's relatively easy to save these variables with localStorage.
function save() {
localStorage.setItem('player', JSON.stringify(player));
localStorage.setItem('score', JSON.stringify(score));
}
function load() {
player = JSON.parse(localStorage.getItem('player'));
score = JSON.parse(localStorage.getItem('score'));
}
We have to remember to convert them to JSON before storing, because localStorage can only accept string values.
Each time you make your game state more complex you have to come back and edit both of these functions. It also has the undesirable effect of forcing the game state to be represented with global variables.
The alternative is to represent the entire state with one atom — in this case a Javascript object.
var state = {
player: { x: 4, y: 3 },
score: 10
};
Now you can write much more intuitive save and load functions.
var SAVE_KEY = 'save';
function save(state) {
localStorage.setItem(SAVE_KEY, JSON.stringify(state));
}
function load() {
return JSON.parse(localStorage.getItem(SAVE_KEY));
}
This pattern allows you to keep state as a local variable and use these functions to work with it.
var state = load();
state.score += 10;
save(state);
In actuality it's quite easy to switch between storage mechanisms, but localStorage is probably the easiest to get started with.
For a small game you'll probably never reach the 5MB size limit and if you do, then you'll also find that the synchronous JSON.stringify and localStorage.setItem operations are causing your game to freeze for a few seconds whenever you save.
If this becomes a problem, then you should probably look for a more efficient way to structure your state and maybe consider designing an incremental saving technique, targeting IndexedDB rather than localStorage.
It really depends on what your looking for.
Cookies are a great way to store data but can be edited by the client and some browsers have cookies turned of.
Web storage has its goods and bads too. If your game has to write masses of data and has lots of players it will quickly use up your bandwidth and may also take time to transfer depending on the clients connection. The upside is that it is fully controllable by you. Once the data has been sent, it can not be edited by the client.
Javascript has some great file I/O utils to help you on the way. Here is a great tutorial: https://developer.mozilla.org/en-US/Add-ons/Code_snippets/File_I_O
If you decide to go with cookies it can be harder or easier depending on your skill. Again, here is a great tutorial: http://www.w3schools.com/js/js_cookies.asp.
Hope this helps!!!
Edit---
When I mentioned client I was really meaning to say player :D

How do I make JavaScript PhoneGap apps to remember something?

I want to make a JavaScript PhoneGap app being able to store information, like log in data or for a savegame, but obviously I'm not able to write into files with JavaScript ansd since this is supposed to work offline I am also not able to run a server script that manages it for me.
I'm pretty sure there is a way to do this and I'd be very thankful for your help!
You can use local storage. Local storage only stores strings, so you'll probably want to serialize JSON when saving to local storage. See is a breakdown of local storage size by browser.
var myData = { foo: "bar" };
localStorage.setItem("myData", JSON.stringify(myData));
var retrievedDataString = localStorage.getItem("myData");
var retrievedData = JSON.parse(myDataString);
Just like "dfsq" sayed, have you tried localStorage?
localStorage.userToken = "SomeData";
But remember, localStorage can only storage a max of 5mb of data and all the data is stored as String, for more than this or more flexibility with the type you will need another solution for your problem.
You better use a database. One of the good options are Firebase. https://www.firebase.com/ . Try its tutorial. It gives you offline capability as well. Also its FREE. ( For 50 concurrent connections )
What about using SQlite plugin for phonegap/cordova?
Cordova SQLite plugin
Many users, many solutions. In my mind the best way to do this would be with a WebSQL Database. You may have a look at http://www.html5rocks.com/de/features/storage - i know this site is in german but the graphic displayed there will give you a little overview. You'll see where you can use what kinds of databases.
WebSQL works like a charme and every of my apps with databases uses webSQL Databases. Its not just a good solution, it is the best one to be consistency. Normally you're using a MySQL DB on a WebServer for Logindata etc. if you have already all your data localy stored inside a WebSQL Database, you have also consistency of your

Is there a simpler method to storage data for chrome apps

I have been trying to find a simple solution(like HTML5 localstorage) to store data for a Chrome app.
I see they have complex storing mechanism # http://developer.chrome.com/apps/storage.html but I hate this method because retrieving data is asynchronous. To retrieve data I have todo something like.
chrome.storage.local.get(key,function(data){console.log(data)});
I hate this method because I cannot assign a variable in a simple manner.
Chrome packaged apps do not support window.localStorage.setItem(); window.localStorage.getItem();
Ended up using sessionStorage since the localStorage is disabled
Whilst its probably not a best practice, you could use
localStorage.setItem('test', 'value');
localStorage.getItem('test'); // == value
Just be careful if storing objects in localStorage - youd need to JSON encode them first.

Internet Explorer Local Storage

I have a application which works great on all browsers but IE. I am using the local database provided with HTML5. I need to store 3 attributes for the users of the application. I know in IE I can't use the database approach and I was thinking of using 3 arrays stored in local storage, one array for each attribute. Is there a better (and easier) way of doing this?
Thanks
For example, I want to store 1) destination 2) where they are from 3) date
So I was thinking I will store an array for destinations, an array fro from locations and an array for dates. Then using some id I can index the arrays and get the corresponding information.
If you need local storage, then you need local storage! Based on the information you describe, I think it's probably too heavy to use in a session cookie.
Check out the docs. Be aware that only IE8+ supports this, so if you need to support other versions - you'll need to do some extra work.
I would personally enable localStorage where possible, then fall back to a round-trip to the server if the browser doesn't support it (and the data is definitely too much for cookies).
Update RE Polyfills
Keep in mind that the polyfills suggested by Rafael will fall back to cookies if the browser doesn't support localStorage etc. Be sure to test with a good spread of data, and keep in mind that it will be sending all that data with each request (which has it's own ramifications).
For IE, you can use a polyfill to simulate a native localStorage: https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills
LocalStorage uses a key:value system. But you can save more than one data in one key, using JSON.Stringify & JSON.parse.
localStorage in IE does not work with this url:
file:///P:/Dropbox/abc_web/ingrid8/ingrid.htm#car..
through network if it works:
file://pedrojelp/p/Dropbox/abc_web/ingrid8/ingrid.htm#car..

Is it possible to serialize Javascript object variable and store into cookies?

Is it possible to serialize Javascript object variable and store into cookies? Or is there other way to accomplish the same thing?
If these objects aren't sensitive (I.e., you don't care if your users modify them), then serializing them into cookies is fine, provided that your objects are small enough not to cause issue.
If your cookies ARE sensitive (you need to depend on them to a level of integrity) or you have large structures, then why not consider storing these serialized objects in a persistant session that is stored on your server. You can then use the cookies as a key or ID to know which session to restore when your visitor returns. In this manner, the size of your serialized objects and whether they might 'fit' in a cookie is no longer relevant.
Another possibility if you not fussy about users modifying things, but do require ample space, (although may not work for all browsers,) is to create a HTML5 'local database' or client-side storage. In this manner, you are both eliminating your concern about the size of the cookies as well as the growing size of your own server-side database. This is probably the best option for sites where you want to store a lot of data per user, but you're not sure if they'll ever come back again. You can always resort to server-side storage (see above) for older browsers.
Here's a particularly good tutorial for getting started with HTML5 local databases: http://blog.darkcrimson.com/2010/05/local-databases/
I hope this is helpful & good luck!
I don't see why not if it fit into length limit of the cookie. I would convert serialized object into say Base64 though.
What problem you're solving?
Yes, it's possible, if the resulting string does'nt exceed the limit of the cookie-size(4KB)

Categories