Show Output
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Set and Get Cookies in JavaScript</title> </head> <body> <script> // A custom function to set cookies function setCookie(name, value, daysToLive) { // Encode value in order to escape semicolons, commas, and whitespace let cookie = name + "=" + encodeURIComponent(value); if(typeof daysToLive === "number") { /* Sets the max-age attribute so that the cookie expires after the specified number of days */ cookie += "; max-age=" + (daysToLive*24*60*60); document.cookie = cookie; } } // A custom function to get cookies function getCookie(name) { // Split cookie string and get all individual name=value pairs in an array let cookieArr = document.cookie.split(";"); // Loop through the array elements for(let i = 0; i < cookieArr.length; i++) { let cookiePair = cookieArr[i].split("="); /* Removing whitespace at the beginning of the cookie name and compare it with the given string */ if(name == cookiePair[0].trim()) { // Decode the cookie value and return return decodeURIComponent(cookiePair[1]); } } // Return null if not found return null; } // A custom function to check cookies function checkCookie() { // Get cookie using our custom function let firstName = getCookie("firstName"); if(firstName != null) { alert("Welcome again, " + firstName); } else { firstName = prompt("Please enter your first name:"); if(firstName != "" && firstName != null) { // Set cookie using our custom function setCookie("firstName", firstName, 1); } } } // Check the cookie on page load window.onload = checkCookie; // Uncomment the following line to delete this cookie // setCookie("firstName", "", 0); </script> <p><strong>Note:</strong> Now if you press the "Show Output" button or refresh the page, you will see a greeting message, if you've entered your first name in the prompt dialog box. See the last line of the JavaScript code to know how to delete this <b>firstName</b> cookie.</p> </body> </html>