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.
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:
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:
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:
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.