In JavaScript, by default, all JavaScript information ‘dies’ when you close your browser. This is by design. So what you have to remember is that each new visit to a page (even a refresh), creates new instances, etc.
This, at times, has created a dilemma for the developer who would like some information to persist between sessions. The “traditional” way to accomplish this task was to use cookies. Cookies are simply text files that store data from a web domainon the client’s machine. They are stored in a name/value format with an expiration date. They are not secure, but neither are they harmful. Cookies received a bad wrap some years ago, but not because of the cookies themselves, but rather vulnerabilities that were exposed by bad programming habits. Allow me to use a simple, but obvious example. I stated that cookies are plain text files. So a developer should never store sensitive information on them, especially since they are stored by domain. So if I stored user login credentials in a cookie, that would not be smart. If that user’s computer were hacked somehow, then the hacker would have access to the domain for that cookie using the stored credentials. So do not do that kind of stuff!
Now I mentioned that cookies were the traditional method. There is a newer method. That came with HTML5. That does not mean that cookies are bad and you need to know how to work with them as they are still in wide use. This just means that when it comes to information persistence, we have an easier method…HTML5 Storage.
HTML5 Storage is the ability to save data in name/value pairs in either a local or session scope. If we store some information in the local scope, then it will survive the closing of the browser. If we store in the session scope, then it dies when the browser closes. Let’s look at two examples…
[code lang=”js”]
// Store information in HTML5 local storage
localStorage.lastName = "Doe";
// Store information in HTML5 session storage
sessionStorage.firstName = “John”;
[/code]
In a future post, I am planning on covering HTML5 Storage in greater detail, but suffice it to say that you can access this data using dot object notation. This is a fairly easy method to access the data. I will also cover cookies since those are still on a lot of sites.
Happy Coding!
Clay Hess