Cookie

A cookie is a piece of data that remains on the visitor's computer after the browser window is closed. Every time a web page is requested from a server, the cookie is added to the HTTP header, so that the server can read the cookie too.

A cookie contains the name-value pair, the expiry date, and the path. Using Javascript, it can be set or returned with document.cookie, which must not be regarded as a normal string property. Applying the assignment = operator to it adds a cookie to the end, instead of replacing the whole series of values with a new value. If the name already exists, only the value of the name will be replaced. The following shows an example of how to set a cookie:

document.cookie='cname=value; expires=Thu, 2 Aug 2001 20:47:11 UTC; domain=google.com; path=/;secure';

expires specifies the expiry time of the cookie. If omitted, the cookie is deleted when the visitor quits the browser.

domain and path designate which locations have access to the cookie in the future. Sub-directories of the path will have access to the cookie too. Note that setting the domain to 'www.example.com' denies access from 'example.com'. If they are not set, it becomes the domain of the page that sets the cookie.

secure, if present, restricts access to the cookie to be via HTTPS only.

Additionally, max-age=max-age-in-seconds specifies the duration till expiration.

samesite={ lax | strict | none } prevents the browser from sending this cookie along with cross-site requests.

When document.cookie is read in an expression, only the name=value pairs are returned as a string, separated by semicolons.: 'cname1=value1; cname2=value2......'

For security reasons, this example won't work in Chrome without a server.
<!DOCTYPE html><html><body><script>
   function getCookie(name){
      let i,x,y,cookies = decodeURIComponent(document.cookie).split(";");
      for (i=0; i<cookies.length; i++){
         const c = cookies[i].trim().split("=");
         x=c[0];
         y=c[1];
         x=x.replace(/^\s+|\s+$/g,"");
         if (x==name) {return y;}
      }
      return "";
   }
   function setCookie(name, v, exp_days){
      var exp_date = new Date();
      exp_date.setDate(exp_date.getDate() + exp_days);
      var c_value = encodeURIComponent(v) + ";expires=" + exp_date.toUTCString();
      document.cookie = name + "=" + c_value;
   }
   function eraseCookie(n){
      setCookie(n,"",-1);
   }
   setCookie("name","Adam",1);
   setCookie("age",25,1);
   setCookie("sex","male",1);
   setCookie("age",30,1);
   setCookie("data","~!@#$%^&*()_+ ",1);
   eraseCookie("sex");
   document.write(document.cookie);
   document.write("<br/>");
   document.write(getCookie("data"));  // ~!@#$%^&*()_+
</script></body></html>

name=Adam; age=30; data=~!%40%23%24%25%5E%26*()_%2B%20;
~!@#$%^&*()_+