Page 158 - CITS - Computer Software Application -TT
P. 158

COMPUTER SOFTWARE APPLICATION - CITS




           A Function to Check a Cookie
           Last, we create the function that checks if a cookie is set.
           If the cookie is set it will display a greeting.
           If the cookie is not set, it will display a prompt box, asking for the name of the user, and stores the username
           cookie for 365 days, by calling the setCookie function:
           Example
           function checkCookie() {
             let username = getCookie(“username”);
             if (username != “”) {

              alert(“Welcome again “ + username);
             } else {
               username = prompt(“Please enter your name:”, “”);
               if (username != “” && username != null) {

                 setCookie(“username”, username, 365);
               }
             }
           }
           All Together Now
           Example

           function setCookie(cname, cvalue, exdays) {
             const d = new Date();
             d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
             let expires = “expires=”+d.toUTCString();

             document.cookie = cname + “=” + cvalue + “;” + expires + “;path=/”;
           }
           function getCookie(cname) {
             let name = cname + “=”;
             let ca = document.cookie.split(‘;’);

             for(let i = 0; i < ca.length; i++) {
               let c = ca[i];
               while (c.charAt(0) == ‘ ‘) {
                 c = c.substring(1);

               }
               if (c.indexOf(name) == 0) {
                 return c.substring(name.length, c.length);
               }
             }
             return “”;

           }




                                                           145

                             CITS : IT&ITES - Computer  Software Application - Lesson 37 - 46
   153   154   155   156   157   158   159   160   161   162   163