Ask if you don’t understand: Cookie vs. session (1. Cookie)

Time:2019-12-20

Cookies are small data stored on the user’s local terminal that is no more than 4KB

Brief description:

/**
 * commonly used
 *@ name username cookie name
 *@ name expires sets the cookie expiration time (UTC or GMT). By default, cookies are removed when the browser is closed
 * other
 *@ name path defines the directory on the web site where the cookie can be accessed
 *@ name domain specifies the web site or domain that can access the cookie
 *@ name secure specifies whether to use HTTPS security protocol to send cookies
 *@ name httponly is used to prevent client script from accessing cookies through the document.cookie property
 **/
 
//Set cookies
document.cookie = "username=jimmy; expires=Mon, 16 Nov 2020 12:00:00 GMT";

//Get cookies
var cookie = document.cookie;

//Delete cookie
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT";

Complete example:

/**
   *Set cookies
   *@ params name key
   *@ params value
   *@ params exitdays (days)
   **/
  function setCookie(name, value, exitDays) {
    var cookieText = name + '=' + value + '; '
    var date = new Date()
    var time = exitDays * 24 * 60 * 60 * 1000
    date.setTime(date.getTime() + time)
    var expiresText = 'expires=' + date.toGMTString()
    document.cookie = cookieText + expiresText
  }

  //Get cookies
  function getCookie(name) {
    var text = name + '='
    var cookieArr = document.cookie.split(';')
    for (var i = 0; i < cookieArr.length; i++) {
      var cookieItem = cookieArr[i].trim()
      if (cookieItem.indexOf(text) == 0) {
        Return cookieitem. Substring (text. Length, cookieitem. Length) // intercept the value value
      }
    }
    return ''
  }

  //Delete cookie
  function delCookie(name) {
    var cookieText = name + '=; '
    Var expires text ='expires = Thu, 01 Jan 1970 00:00:00 GMT '// earlier than the current time
    document.cookie = cookieText + expiresText
  }

  //Detect cookies
  function checkCookie() {
    var user = getCookie('username')
    if (user != '') {
      Alert ('Welcome '+ user +' visit again ')
    } else {
      User = prompt ('Please enter your name: ',')
      if (user != '' && user != null) {
        setCookie('username', user, 30)
      }
    }
  }

Recommended Today

ES6 array sorting: more recommended methods and techniques than Es5

Original link: HTTPS: / / dsx2016. COM /? P = 692 WeChat official account: Senior brother 2016 ECMAScript ECMA ScriptyesECMA-262The name of the standardized scripting language. althoughJavaScriptandJScriptAndECMAScriptCompatible, but contains more thanECMA ScriptFunction. The following table is divided into four modules: ECMAScript 1st Edition (ECMA-262)Corresponding to the first edition andES5Previous versions (this article only) ECMAScript 5.1 […]