HTML - Manipulating Cookies

In HTML, cookies are small pieces of data that are stored on the user's computer by the web browser. Cookies are created by websites to remember information about the user, such as login details, preferences, and shopping cart contents.

When a user visits a website, the website can set a cookie by sending an HTTP header to the user's browser. The browser then stores the cookie on the user's computer and sends it back to the website on subsequent requests.

Cookies can be either persistent or session-based. Persistent cookies are stored on the user's computer for a specific amount of time, such as a month or a year, and are used to remember user preferences across multiple visits. Session-based cookies, on the other hand, are only stored temporarily and are deleted when the user closes their browser.

Create cookies using JavaScript within an HTML page

In JavaScript, cookies can be created and manipulated using the document.cookie property. This property allows you to read, write, and delete cookies as needed.

Following is an example of how to create a cookie using JavaScript:

document.cookie = "username=criswalter";

In this example, setting a cookie named "username" with a value of "criswalter". This cookie will be saved in the user's browser and will be available for retrieval on subsequent visits to the website.

To retrieve the value of a cookie, you can use the document.cookie property again:

const username = document.cookie.split(';').find(cookie => cookie.includes('username')).split('=')[1]; console.log(username); // output: "criswalter"

In this example, retrieving the value of the "username" cookie by splitting the document.cookie string into an array of individual cookies, finding the cookie that contains the string "username", and then extracting the value of the cookie.

To update the value of a cookie, you can simply set the cookie again with the new value:

document.cookie = "username=criswalter";

In this example, updating the value of the "username" cookie to "criswalter".

Finally, to delete a cookie, you can set its expiration date to a date in the past:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC";

In this example, deleting the "username" cookie by setting its expiration date to a date in the past.

Full Source | HTML and JavaScript

Following is an example of how to create, read, update, and delete a cookie using JavaScript within an HTML page:

<!DOCTYPE html> <html> <head> <title>Cookie Example</title> </head> <body> <h1>Cookie Example</h1> <label for="username">Username:</label> <input type="text" id="username" /> <button onclick="saveUsername()">Save Username</button> <button onclick="deleteUsername()">Delete Username</button> <p id="username-display"></p> <script> // Function to save the username as a cookie function saveUsername() { const username = document.getElementById("username").value; document.cookie = `username=${username}; expires=${getExpirationDate(7)}`; displayUsername(); } // Function to delete the username cookie function deleteUsername() { document.cookie = `username=; expires=${getExpirationDate(-1)}`; displayUsername(); } // Function to display the username if it exists function displayUsername() { const username = getCookie("username"); const usernameDisplay = document.getElementById("username-display"); if (username) { usernameDisplay.innerHTML = `Your username is: ${username}`; } else { usernameDisplay.innerHTML = "No username saved."; } } // Function to get the value of a cookie by name function getCookie(name) { const cookies = document.cookie.split("; "); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].split("="); if (cookie[0] === name) { return cookie[1]; } } return null; } // Function to get the expiration date for a cookie function getExpirationDate(days) { const date = new Date(); date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000); return date.toUTCString(); } // Display any existing username on page load displayUsername(); </script> </body> </html>

In the above example, an HTML page with a text input and two buttons: "Save Username" and "Delete Username". When the user enters a username and clicks "Save Username", use JavaScript to create a cookie named "username" with the value of the entered username. When the user clicks "Delete Username", use JavaScript to delete the "username" cookie.

Also have a function called displayUsername that checks if a "username" cookie exists and displays the value on the page. Use the getCookie function to retrieve the value of the cookie by name, and the getExpirationDate function to set the expiration date for the cookie.

Finally, call the displayUsername function on page load to check if a "username" cookie already exists and display it if it does.

Conclusion:

It's worth noting that while cookies are a useful tool for websites to enhance user experience and personalize content, they can also be used for tracking user behavior and potentially compromising user privacy. As a result, many modern browsers allow users to block or delete cookies, and some websites require users to consent to the use of cookies before accessing the site.