This article explains how to use JavaScript to set values in cookies and display those values on a different page. In the previous article, Guide to Using sessionStorage: How to Share Data Across Pages with JavaScript, we introduced sessionStorage. This time, we will introduce a method using cookies. By using cookies, data can be retained even after the session ends or the browser is closed, allowing for longer-term data management.
What is a Cookie?
Cookies are small pieces of data that a website stores on a user’s browser. This allows specific settings or information to be automatically loaded when the user revisits the site, enhancing the user experience. For example, cookies can be used to store language preferences or login information.
Cookies can be easily set, retrieved, and deleted using JavaScript. In this article, we will demonstrate how to set values in cookies and retrieve and display them on a different page.
Example of a Page That Sets Cookie Values (index.html)
First, create a page to set cookie values. In the example below, we set two cookies: “ck1=Cookie1” and “ck2=Cookie2.” These cookies are valid for one minute and will be automatically invalidated after that.
<h1>This page sets values in cookies to be displayed on another page</h1>
<br>
This page sets the cookies "ck1=Cookie1" and "ck2=Cookie2."<br>
Click the link below to display the value set for the "ck1" key on another page.<br>
The value will be displayed in the browser's alert dialog message.<br>
<br>
<br>
<a href="page2.html">Display the value of the cookie set for the "ck1" key on another page>></a>
<script type="text/javascript">
var now = new Date();
now.setMinutes(now.getMinutes() + 1); // Valid for 1 minute
// Cookies valid for 1 minute
document.cookie = "ck1=" + encodeURIComponent('Cookie1') + ";expires=" + now.toUTCString();
document.cookie = "ck2=" + encodeURIComponent('Cookie2') + ";expires=" + now.toUTCString();
</script>
This code uses document.cookie
to set cookies. The encodeURIComponent
function is used to encode cookie values so that specific characters (e.g., spaces or non-ASCII characters) are correctly stored. The expires
attribute specifies the expiration time for the cookies.
Example of a Page That Displays Cookie Values (page2.html)
Next, here is how to retrieve and display values set in cookies on another page. The code below uses document.cookie
to retrieve all cookies, splits them into key-value pairs using the split
method, and displays the value for a specific key.
Finally, the cookies are deleted by setting their expiration to 0 or a past date.
<h1>This page displays the value set in the "ck1" cookie in a browser alert dialog<br>and then deletes all the cookies.</h1>
<br>
<br>
<a href="./"><< Return to the page that sets cookies</a>
<script type="text/javascript">
var cookies = document.cookie;
var cookiesArray = cookies.split(';');
for (var c of cookiesArray) {
var cArray = c.split('=');
if (cArray[0].trim() === 'ck1') { // When the cookie key is ck1
alert(decodeURIComponent(cArray)); // Retrieve the value of key ck1
}
}
// Delete cookies
var now = new Date();
now.setFullYear(now.getFullYear() - 1);
for (var c of cookiesArray) {
var cArray = c.split('=');
// Setting cookies with an expiration date of 0 or a past date deletes them
document.cookie = cArray[0].trim() + '=;max-age=0';
document.cookie = cArray[0].trim() + '=;expires=' + now.toUTCString();
}
</script>
This code first retrieves all cookies with document.cookie
and splits them into individual cookies using split(';')
. Then, it splits each cookie into a name and value using split('=')
, identifies the specific cookie (“ck1”), and displays its value using alert
. Finally, the cookies are deleted by setting their expiration date to a past date.
Demo Page: Display Values Set in Cookies on Another Page
Try the demo page that uses the above method to display values set in cookies on another page. Check it out!
Display Values Set in Cookies Demo
Conclusion
Cookies are a powerful tool for storing data on a user’s browser. With JavaScript, you can easily set cookies and retrieve and display their values on another page. Additionally, specifying the expiration date of cookies allows you to control the duration for which data is retained.
By effectively using cookies, you can enhance the user experience in various scenarios. Moreover, since cookies can be easily deleted, there is no concern about unnecessary data accumulating indefinitely.
This article provided a clear explanation of how to use cookies for data retention and display. Getting familiar with using cookies will expand your web development capabilities, so be sure to give it a try!
※ Please use this content at your own risk. Do not copy the Google Analytics tag included in the head tag of the demo page.