Not allow localstorage to be changed by user - javascript

I use localstorage to store things like highscore in this game: http://wacky2048.ga/
If you inspect element and on the top navigation bar (where you see Elements ... Performance), then click the >> button, click Application, you can see all the localstorage items, and if you double click, you can change it. You may need to make a move and refresh.
A lot of people know this trick so the highscore becomes meaningless.
Is there any way to stop this? I store integers and JSON stringified things (in case you want to suggest a encoding method).

The better solution would be store the data in the server. But if you really want to use localstorage consider storing the JSON as a jwt token and encrypt it using a private key which user doesn't have access.
Also when your app access that data in the localstorage always check for validity. If the token is invalid, what you can do is re fetch the information from the server.
Like i said before this is more of a dumb approach. Storing data in the server would be a better solution.
Edit: To hide the private key you could use environment variables like NODE_ENV (this depends on the framework you are using)

Related

Easiest way to store little information

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.

Find the last visited URL in javascript with history

I know about document.referer and this is not what I'm looking for.
It could probably be a solution but I want to retrieve it in local without using server.
Steps :
I'm pushing a new state in the current url of my page with history.pushState('','','#test')
I'm going to the next page.
And now I want to retrieve the URL but history.previous has been erased since Gecko 26.
Is there an other way of getting this value except from using cookies or sessionStorage?
One way of doing it would be to put the value in a parameter of the next page address, like so:
http://server.com/next-page-address/whatever.html?prevData=RequiredStateData
Note that using this approach, you might be exposed to users changing RequiredStateData in a malicious way. You can protect yourself using encryption or some checksum field.
So my problem was that there is no option for that purpose in local without a server environment.
If you find this question it's that you're probably in the same problem as me so the only option I found was to use.
sessionStorage.setItem('foo',val) and retrieve it with sessionStorage.getItem('foo').

"Null" HTML DOM Element?

I'm writing a framework which uses javascript/html as the client and it-doesn't-matter as the back end.
From time to time I have a need to store data in the HTML DOM. Ideally I'd like to store the data against a DOM element, but I want this element to have no UI impact.
At the moment I'm thinking I'll use a <span> with no text content and decorate it with attribution so that my framework can pick up that it is a data container and behave appropriately.
Is there a better choice? (For the avoidance of doubt, I know there are other ways I could do things - I'm not interested in these, purely in what the best HTML element to use to contain data without having a UI impact).
Edit (explanation of architecture):
I've created a server-side technology which is based on top of a generic reporting engine I've previously created. This server-side thing essentially works as a web-server - this might seem like an unusual choice to make but, given organisational constraints, it's the best choice - for the sake of argument, assume this is true. One of the things I need this system to do is to generate dynamic forms to capture data which is in a tree-like form. This has been fine and has worked well - my question is because when a sub-form is hidden (for example, the user has made all required decisions in a given sub-section of the data), I destroy the data capture elements - if the form is embedded within a parent form which needs access to the data captured in a destroyed sub-form, I need a way of embedding the data into the DOM so it can be collected to be passed back to the server. The requirements are a lot more complicated that this, but it'll take far too long to detail them all.
Well (and for the avoidance of doubt), the HTML elements are not supposed to store data. If you really want to, use the <input type="hidden"> element.
For your purpose, I recommend (in that order) using localstorage or cookie or web database.
here are some resources :
localstorage : http://diveintohtml5.info/storage.html
cookie : http://www.the-art-of-web.com/javascript/setcookie/
web database : http://www.tutorialspoint.com/html5/html5_web_sql.htm
As JLRishe pointed out, if you need, for whatever reason, a text node storage, then span is a good choice as div is (and as lot of elements are as long as you display: none them).
You could just create javascript objects...
var myData ={
property1:"aaaaa",
property2:500,
property3:{morestuff1:"AAA", ... },
property3:["list1", "list2", ... ],
....
}
Easy to access and easy to manipulte within the DOM if you need.
No UI impact.... (no render)
The obvious choice here is to use HTML data attribute. If you have a table and want to store info about the table that is not shown to the user - you could just:
<table id="mytable" data-id="2000" data-rows="20" data-whatever="whatever">
You could then get it with jQuery easely with:
$("#mytable").data('rows');
Which would give you 20.
It's not good practice to store data in the DOM, if you're not actually using it for the purpose of layout. Yikes!
To better suit your needs, HTML5 provides a JavaScript API for handling client side storage. Depending on your circumstances, you have 2 options to choose from. The APIs are exactly the same, the only difference is the lifetime of the storage.
They are:
localStorage: Local storage is persistent; data stored in local storage is even available to the webpage after the user closes the browser completely and reopens it.
sessionStorage: As the name says, this data is only available for the current session.
Here's a link that will help you better understand these APIs so you can solve your particular problem: http://www.w3schools.com/html/html5_webstorage.asp

Optimizing local storage and search

I have a web application built in .NET
During a session, the user has to access a dictionary value, that is populated from the database. The user makes frequent calls to it.
I want to cut down the HTTP calls and want to bring the dictionary value to the client and access it from there.
I wanted to understand what would be the best practice to store this dictionary value locally in such a way that retrieving data is very quick?
What I'm trying to really do is similar to what FaceBook does with "#", so when you write #Name, it quickly makes a search in the database and replaces the text with the link. In my case, I have a fixed set of data to search from and usually it is not beyond 10-15 name-value pairs.
I contemplated of storing values in cookies, but don't really know if there would be any storage limit and am also unaware of how quick the retrieval would be.
Any help is much appreciated.
Thank You
If the dictionary is static then you can use JSON.stringify and localStorage to store it. This way the user only needs to load it the first time they ever visit your site. After it is stored in localStorage, I would suggest loading it into a JavaScript object using JSON.parse each time the page is loaded to speed up searching since a JavaScript object works like a hash table.
You could then add a simple check each time the page loads to see if the dictionary needs to be refreshed.
var globalDictionaryHash = null;
function loadDictionary()
{
if (localStorage.getItem("my_dict") == null)
{
localStorage.setItem("my_dict", JSON.stringify(myObjectFromAJAXCall));
}
globalDictionaryHash = JSON.parse(localStorage.getItem("my_dict"));
console.log(globalDictionaryHash['key']);
}

Store Javascript variable client side

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

Categories