Understanding Local Storage & Cookies in Javascript - javascript

I have a form on my page with text boxes, radio buttons and drop down menus that ask questions about students. The options selected from these will later be used to make a div containing each student's content. My directions say to save the list to local storage. I'm confused on what exactly this means. I tried looking this up and cookies kept coming up. I thought these were 2 different things. I'm confused on the concept of local storage. I've searched this on Google and Stack and have read what ever I could find related to these topics. I think I need this explained in a simple way rather then reading a textbook definition or answers to questions people have asked about there code relating to cookies and local storage. Can someone explain these 2 topics? Are cookies and local storage the same things? I'm not sure if it's different for other languages but I'm using Javascript.

localStorage is an API that the browser provides to allow you to read and write data. You can kind of imagine it as a single large JavaScript object, storing data values under different keys. Using it is easy: localStorage.setItem(key, value) (for some key and value, e.g. localStorage.setItem('test', 23)) to write a value and localStorage.getItem(key) to read/access that value. Details and examples can be found here
Cookies are accessed through the API document.cookie. document.cookie also uses pairs of keys and values (the cookies) to store data; however, the approach for reading and writing cookies is different. To create a new cookie, you enter document.cookie = "key=value" (for some key and value, e.g. document.cookie = "test=23"). To see all cookies, enter document.cookie, which will spit out all cookies as a string of keys and values, separated by semicolons (e.g. "test=23; someOtherKey=59"). Unfortunately, this makes reading cookie values a little trickier than with localStorage; the simplest way to get the value for a single key would be to use a Regular Expression, a specific pattern for matching text. More details and examples can be found here.
In terms of how you use them, they're similar in that they both are used for storing data. However, cookies are mainly sent to the browser from the server along with the page; localStorage, in contrast, is only accessible to the JavaScript code in the browser.
Hope this helps!
[EDIT]
See also

Cookies and localstorage are not the same things.
Cookies
Cookies are small files that contain information useful to a web site — such as password, preferences, browser, IP Address, date and time of visit, etc. Every time the user loads the website, the browser sends the cookie back to the server to notify the website of the user’s previous activity. Cookies have a certain life span defined by their creators and it expires after the fixed time span.
localStorage
The localStorage property allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions. That means it won't clear until you remove it. In another way, localStorage has no expiration time.
Add data to localStorage
localStorage.setItem('myCat', 'Tom');
Remove Item
localStorage.removeItem('myCat');
Remove all items
localStorage.clear();
Also, there is another thing called sessionStorage. Which is same as localStorage but data only stored until the browser session is closed.

Related

Is it possible to keep variable values after page reloaded in JavaScript without using cookie and local storage?

I am trying to keep values for a page over user interaction. I know I can do it using cookie and local storage. But I am curious to know that is there any way to do it without using cookie and local storage. If it is possible then how?
Actually I am asking to do it without any storage.
Update url for each action made by user so you can retain the parameters you want on page reload, I don't think we have any other way
IndexedDB is another option for client-side storage. Its API is a bit complex though, so to use it, you might want a library like localForage instead.
Another option is to save the values by saving them in a database on the server, though for reliable retrieval without storing any information client-side, the user will have to be able to input something unique to them (such as username/password - the server checking their IP addresses likely won't be enough, since IP addresses are often shared)

how to maintain check boxes state across jsp pages whenever you come back on a page using javascript or jsf without storing it into database

i want my all check boxes checked whenever i come back from other pages, i want to maintain their states across pages using javascript.
I think you are asking how to store state for an individual session between requests. In this case, that state is checkbox values.
You have a choice to make first: do you want to store the data on the client (in the browser) or on your server?
Server Side
You can store this state on the server side with or without a "database" depending on how pedantic you want to be about the term.
If what you want is to avoid configuring an SQL RDBMS, you might find that the built-in storage options from most Java Servlet containers will work. In Tomcat, you can just use your Session objects as normal, but configure a "File Based Store" instead of a "JDBC Based Store." This will store session data to disk in files. Alternatively you can use StandardManager which uses in-memory storage, but does not persist session state across restarts.
Put simply, these will create a Java Map for each JSESSIONID issued by your server, and then keep the maps in memory, on disk, or in a JDBC database. For more information see: https://tomcat.apache.org/tomcat-7.0-doc/config/manager.html
Client Side
Here you have a few options as well. The driving factor is what level of browser you wish to support. If you can tolerate restricting your users to those who use a browser with HTML5 web storage and JavaScript enabled, things are pretty easy. If not, you can accomplish the same thing with a cookie.
The big downside to client-side storage is trust. Users (or software on their computer) can modify client-side storage. This goes for cookies, localStorage, and sessionStorage. Many developers forget this and introduce security vulnerabilities because of it. If this is for a real production web application, you'll want to wrap your state in an authenticator.
Here's a the first in a three article series on a way to convince your servlet container to put session state into cookies in a way that is transparent to your servlets. It is missing authentication, but you can add it by following guidance such as this bit from Rob Winch.
Now What?
Ok. You've decided to use client- or server-side storage for your checkbox values. Now what?
A simple (usually wrong) option is to store the checkbox input names and values in a map:
{"boxFoo": true,"BarBox":false}
The reason this is usually wrong is that it fails to distinguish which form your user was visiting. It means that if you apply this strategy to more than one form on your site, you'll have to worry about name collisions.
The next evolution is to have a structure keyed by form name and then field name. This would be a map like the following:
{ "formA": {"boxFoo": true,"BarBox":false},
"formQ": {"checkAlpha":true,"BetaCheck":false } }
This works, but will have annoying behavior when your users use multiple tabs. You can make that behavior more predictable for your users by using per-tab identifiers -- at the expense of space in your session object -- or by using AJAX to keep the fields in sync -- which has its own perils. Or you can do what most people do an just assume that the last submitted form overwrites the state from all previous ones, tabs be damned. That's much simpler to code, but more annoying to users.
I can propose some ways :
send http params (in hidden field) with check boxes flags which must stay checked in each new page requested by your application . You can factorize it with a function but it stays cumbersome to do.
store the check boxes marker flag in the http session. If the check boxes must stay checked in all the life of your user, it may be a suitable solution. Use may use a backing bean session for it as you use JSF.
Nevertheless, store the minimum of information in it.
store the information in a shared applicative cache to retrieve it. In this way, you stay stateless and you have not the drawback of the session if you use clustering in your servers.
There is maybe better as alternative.
You have to bind the value with a backing bean. As long as the backing bean is having the appropriate scope it will be retained on the page when you navigate to it.

Javascript substitute for cookies

In javascript, is there a clear and concise substitute for cookies? I am currently storing game saves in cookies, and looking for a way to make them harder to accidentally (or purposely) delete.
There are really not that many places to store data. You can really store it in two places:
The client's machine: There are other options besides cookies, but they are just as likely to be cleared if the user wishes. Cookies are probably still the easiest way to go about this.
Your server: You could create some login system or other to store the data locally and then determine what saved data corresponds to which client.
I still think your best option here is to use cookies. Most games rely on cookies or browser saved data anyways and clearing that within the browser deletes progress.
If you really do not like cookies:
With the introduction of HTML5 you can now save data within the browser, for more information see here: http://www.sitepoint.com/html5-web-storage/. This could allow for more data to be saved and speed up the requests, but also will probably get cleared if the user clears their cookies.

Chrome Content Scripts: Save to database

So I am making a pretty simple Chrome content script (or should be if it's allowed).
So I want to be able to save certain things on a webpage for future reference. So for example, say I go to quora and search for something. I want to be able to hold onto that query for, say, a the next few webpages the user goes to. I was thinking if I could save values to a database from a content script that would work, if not just a simple way to save it in a cookie or something could work.
Any thoughts? Is this possible with a content script?
localStorage
There's a special API to store small amounts of data in browser called localStorage. It is very useful to store key-value pairs.
localStorage["key1"] = "value1";
console.log(localStorage["key1"]); // value1
The point is that localStorage is similar to cookies in terms of data persistence. This means you can get saved data even after you exit the browser.
Nice read about localStorage: http://diveintohtml5.info/storage.html.
chrome.storage (best way for you)
Actually, Chrome has its own analogue of localStorage. It's called chrome.storage API. If you use content script, I think this is the best way for you. The point is that your content script can directly access data, there's no need of background page. And it also should be mentioned that you can store objects using chrome.storage (localStorage stores only strings).
As usual, there's a nice documentation from Google for its API: http://developer.chrome.com/extensions/storage.html
IndexedDB
If you need to store big amounts of data, the best way to do it is to utilize browser databases, such as IndexedDB or Web SQL (Alert! Web SQL is deprecated since 2010).
Read more about IndexedDB:
https://developer.mozilla.org/en/docs/IndexedDB
http://www.html5rocks.com/en/tutorials/indexeddb/todo/
More about Web SQL:
http://html5doctor.com/introducing-web-sql-databases/

How to safely store and access user session data

I am currently learning about security aspects in web applications.
My application used to identify the current user by a cookie which was created on successful login. It contained the user's id. Every time the user has made a request to the database, my application would use that id to select only those results that were associated with this id.
However, as I learned, it would be no problem at all to simply change that cookie's value and therefore get access to another user's data.
My issue now is: how would I safely store such data and make it available to both PHP and Javascript?
I thought of HTML5 sessionStorage, but that would be vulnerable too.
My second thought was to store it by PHP only in a $_SESSION variable, but then I could not access its value via Javascript.
I feel like I can not wrap my head around the basic concepts of how to create a secure and functional user-management system.
Any help will be appreciated.
I would store the user id data only in the session. Why do you need cookies?
To communicate between JS and PHP use ajax. Best library for this is jQuery
.
Simple solution:
Add a userKey field to the database.
When user logs in, generate a random unique string and save it in DB
Save this string in cookie. Save user ID in cookie.
On the next visit, select from the database user with the corresponding userKey and ID.
It is somewhat secure, because the string is random, so only bruteforce helps.
Longer the string - harder to bruteforce.
The solution is simple, it can be upgraded by using crypting of ID, checking IP, etc.

Categories