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
Related
I am quite new to coding so apologies if I'm asking an obvious question. I have managed to create a little web app in html/JavaScript that takes user input and transforms it and dumps it into a variable that I am interested in. All in all, all the information that I want to extract is in the form of an array comprising of 20 integers in the JavaScript code.
What I want to do now is find how to store that information so when somebody fills out the inputs and submits the form - I can have access to it. I have looked around the web and the common suggestion seems to be SQL database. I was just wondering if there is a simpler way of going about it, especially considering the tiny amount of information I need to store?
Well, if you just want to store the data on the website itself for each individual client, localStorage is the way to go. In other words, if you want to just store a bit of data for later, localStorage allows you to store data that is accessible the next time the user loads the page. This data can't be shared with other users, but if your app doesn't need too much security, or data sharing between users, localStorage is the way to go. However, the user can control what's in localStorage, so you need to make sure that you don't store anything sensitive there. In addition, you won't be able to see the data actually stored in localStorage on your website as the developer. All your handling has to be done on the client side. Every browser supports it, and it's really simple to use.
First off, you can set a value in localStorage like this:
localStorage.foo = "bar";
Then, you can get a value from localStorage like this:
localStorage.foo; //Returns "bar"
The only problem is, localStorage values can only be stored as strings.
So, in order to store an array (like you wanted to), you can do:
localStorage.arr = JSON.stringify([1, 2, 3]);
This turns the array into a string.
Then, to get the array from localStorage:
JSON.parse(localStorage.arr)
That's pretty much all you need to know for what you are describing.
If you want the full story on localStorage, visit: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
I hope this answer helped.
I am writing an application that derives a lot of image data, and doing that takes qutie some time, and during that time the user is waiting.
When I have derived the data I would like to store it in case the user wants to see it again anytime soon. I have been going through some local storage methods in html5 and the most promising for my case seems to be localStorage.
A downside to localstorage is that it tends to not allow that much data to be stored, 5Mb in most cases, and my thoughts are to every time i derive some data, to store it in localStorage. The problem arises when those poor little 5MB get filled up, and then I would like to delete the oldest element from the memory, bu there seems to be no easy way of doing that as everything is just stored in key-value pairs.
So I'm not quite sure how to proceed with using localStorage in this case.
Is there any module or something that can make using localStorage in the manner described above easier?
You can use
1) IndexedDB to store huge data but it will only work in latest browser except Opera mini.
2) OR, store your data in memory and later on to localstorage or vice versa.
3) You can always put your time tag with each key you are storing. you can traverse through keys having specific format to get the oldest key in store and you can delete it easily.
4) you can also put your time stamp in data with your image data, in this case you will not have to extract all keys but complete data objects from the store.
I would suggest you IndexedDB option to overcome your size limitaions.
Hope this will help.
In the end i used this module: https://gist.github.com/ragnar-johannsson/10509331.
Using it the oldest values get deleted if there isnt enough memory to add a new one.
I have a lobby written in HTML5 / javascript. A .json file provides a few config parameters for the lobby and for the various other HTML5 games that can be launched from it. These parameters can either be passed to the games in the window.open string ( in the form of:
window.open(http://www.myLovelyDomain.com/index.html?username=bob&token=aaaXXX")
or could be held in localStorage and accessed by the game following it's launch.
My question is, what is the best (most secure/likely to cause least errors/etc) method? I know users can turn off localStorage, but I don't know how many do. Any thoughts?
Advantages of localStorage over URL query strings
Less likely to be user edited
Less likely to be copy&pasted to someone else
Can persist across sessions
Wider choice of characters
(Marginally) less bandwidth usage (shorter GETs)
Can store whole files
Invisible to basic user
Disadvantages
Server doesn't get access to the variables without additional ajax
May be harder to debug
May need extra checks if things change every session (or consider sessionStorage)
Not supported by old browsers
Can't use cross-domain directly (may be advantage, depending on how you look at it)
For supported list and max sizes see here.
Let's say I'm making an HTML5 game using JavaScript and the <canvas> The varaibles are stored in the DOM such as level, exp, current_map, and the like.
Obviously, they can be edited client-side using Firebug. What would I have to do to maximize security, so it would be really hard to edit (and cheat)?
Don't store the variables in the DOM if you wish a reasonable level of security. JavaScript, even if obfuscated, can easily be reverse engineered. That defeats any local encryption mechanisms.
Store key variables server-side and use https to maximize security. Even so, the client code (JavaScript) is quite vulnerable to hacking.
You can use Object.freeze or a polyfill or a framework which does the hiding for you.
Check out http://netjs.codeplex.com/
You could also optionally implement some type of signing system but nothing is really impenetrable. For instance objects locked with Object.freeze or Object.watch can still be manually modified in memory.
What are you really trying to accomplish in the end?
What you could do is send a representation of the matrix of the game or the game itself or a special hash or a combination of both and tally the score at the server... causing the user to not only have to modify the score but to correctly modify the state of the game.
Server-side game logic
You need to keep the sensitive data on the server and a local copy on the browser for display purposes only. Then for every action that changes these values the server should be the one responsible for verifying them. For example if the player needs to solve a puzzle you should never verify the solution client side, but take for example the hash value of the ordered pieces represented as a string and send it to the server to verify that the hash value is correct. Then increase the xp/level of the player and send the information back to the client.
Anything that is living in the client can be modified. That is because in MMORPG the character's data is living on the server, so players can't hack their characters using any memory tools, hex editor, etc (they actually "can", but because the server keep the correct version of the character's data is useless).
A good example was Diablo 2: you have actually two different characters: one for single player (and Network playing with other players where one was the server), and one for Battle.net. In the first case, people could "hack" the character's level and points just editing the memory on the fly or the character file with an hex editor. But that wasn't possible with the character you was using on Battle.net.
Another simple example could be a quiz where you have a limited time to answer. If you handle everything on client side, players could hack it and modify the elapsed time and always get the best score: so you need to store the timestamp on the server as well, and use that value as comparison when you get the answer.
To sum up, it doesn't matter if it's JavaScript, C++ or Assembly: the rule is always "Don't rely on client". If you need security for you game data, you have to use something where the clients have no access: the server.
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