js manipulate cookies

what is a cookie

A cookie is a variable stored in a visitor's computer and is sent when the same computer requests a page through a browser. JavaScript can create and retrieve the cookie value.
Each cookie is in the form of a key-value pair, such as "username=123;userid=321".
The cookie uses escape() to encode the unrecognized ";", ",", "=" and spaces. Correspondingly, after retrieving the value, it needs to be decoded with unescape() to get the original cookie value.

cookie cross domain

By default, cookies created under a certain page can be accessed by other pages in the directory and pages in subdirectories, but cannot be accessed by pages from different sources, such as www.xxxx.com/views/a.html The cookies below can be accessed by www.xxxx.com/views/b.html and www.xxxx.com/views/index/c.html, but not by www.xxxx.com/d.html, which involves Same Origin Policy.

The same-origin policy means that client scripts from different origins cannot access or read and write resources of the other party without explicit authorization. The origin refers to the protocol, domain name, and port number. For example, http://www.xxx.com:80/, the protocol is http or https, the domain name is xxx.com, and the port is generally 80 by default.

To solve the cross-domain problem of cookies, such as the cross-domain of www.google.com and gmail.google.com, you can use document.domain to set the same domain name.

create cookie

The parameter holds the name, value and expiration date of the cookie

function setCookie(c_name,value,expire){
  var date = new Date();
  date.setSeconds(date.getSeconds()+expire);
  document.cookie = c_name+'='+escape(value)+'; expires='+date.toGMTString();
}

read cookies

function getCookie(c_name)
{
    if(document.cookie.length>0){
        let c_start = document.cookie.indexOf(c_name+'=')
        if(c_start!=-1){
            c_start = c_start+c_name.length+1
            let c_end = document.cookie.indexOf(';',c_start)
            if(c_end == -1) c_end=document.cookie.length
            return unescape(document.cookie.substring(c_start,c_end))
        }
    }
    return ""   
}

delete cookies

function delCookie(c_name){
    setCookie(c_name,'',-1)
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324548217&siteId=291194637