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!
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.
The document.cookie
property is used for setting, reading, altering and deleting browser cookies.
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;
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(; );
The new HTML5 localStorage
Object is another way to store data locally:
localStorage.setItem('itemname','contents');
localStorage.getItem('itemname');
. You can check if an item exists using truthy values (i.e. if(localStorage.getItem('itemname'))
)localStorage.setItem
as described above.localStorage.removeItem('itemname')
.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.