Okay, I want to make a corny joke about cookies, but alas, I will refrain. I will stick to why are they called cookies?
Wikipedia (where everything is accurate), outlines their origin story below.
The term “cookie” was coined by web browser programmer Lou Montulli. It was derived from the term “magic cookie”, which is a packet of data a program receives and sends back unchanged, used by Unix programmers.
So, where do we see cookies? They are used on almost every major website today. Why do they use them? Cookies keep track of user information. The interesting part is that this was and still is a privacy concern. As such, when you develop a site using cookies, you want to avoid inserting and storing any sensitive data. User profile information is fine (e.g., “Welcome back Bob!”) where the name Bob is stored in a cookie after they log in.
How can we see our cookies? In Chrome, go to the three dots in the upper right-hand corner. Select Settings, scroll down, and click on Advanced. Then, scroll down and click on Content Settings. Click on Cookies and click on See all cookies and site data.
Now, let’s see how cookies are stored and retrieved in JavaScript. Again, we need two pages so we can carry information from one page to another.
This time the first page will look like this:
<html>
<head>
<title>
Cookies
</title>
<script>
function sendInformation()
{
var information = document.getElementById("info").value;
document.cookie = "information=" + information;
window.location="Cookie2.html";
}
</script>
</head>
<body>
<input type="text" id="info">
<button id="btnSubmit" onclick="sendInformation();">Submit</button>
</body>
</html>
While the second page looks like this:
<html>
<head>
<title>
Cookies
</title>
<script>
function getInformation()
{
document.getElementById("message").innerHTML = document.cookie;
}
</script>
</head>
<body onload="getInformation();">
<div id="message"></div>
</body>
</html>
We use document.cookie to store and retrieve information. We will have to add more techniques to get separate the name and value from one another. We will learn how to do that in the next section on arrays. One final note, to test this code, you want to run this in Firefox. We can do it in Chrome through a local webserver (live server in Atom or VS Code), but otherwise, clicking on the file will not work.