Example of JS using cookie to save user login information

Posted by epp_b on Fri, 14 Feb 2020 16:53:50 +0100

This article describes how JS uses cookie s to save user login information. To share with you for your reference, as follows:

Generally, cookies and session s are used to store information in web development. Sessions exist in the memory of the server, while cookies exist in the client. Therefore, js can directly operate cookies to store and read information.

js stores the general writing method of cookies, such as: document.cookie = "userName=admin";, if there are multiple key value pairs: document.cookie = "userName=admin; userPass=123";
Here is the js operation cookie to save the user's login information:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript" type="text/javascript">
function addCookie(name,value,days,path){  /**Add settings cookie**/
  var name = escape(name);
  var value = escape(value);
  var expires = new Date();
  expires.setTime(expires.getTime() + days * 3600000 * 24);
  //Path = /, indicating that the cookie can be used in the whole website, path=/temp, indicating that the cookie can only be used in the temp directory
  path = path == "" ? "" : ";path=" + path;
  //GMT(Greenwich Mean Time) is Greenwich mean time, now standard time, coordinated universal time is UTC
  //Parameter days can only be numeric
  var _expires = (typeof days) == "string" ? "" : ";expires=" + expires.toUTCString();
  document.cookie = name + "=" + value + _expires + path;
}
function getCookieValue(name){ /**Get the value of the cookie according to the key of the cookie**/
  //Find the value corresponding to key by processing string
  var name = escape(name);
  //Read cookie properties, which will return all cookies for the document
  var allcookies = document.cookie;
  //Find the start location of the cookie named name
  name += "=";
  var pos = allcookies.indexOf(name);
  //If a cookie with that name is found, extract and use its value
  if (pos != -1){                       //If pos value is - 1, search "version =" failed
    var start = pos + name.length;         //Where cookie values start
    var end = allcookies.indexOf(";",start);    //Search the location of the first ';' starting from the location where the cookie value starts, that is, the location where the cookie value ends
    if (end == -1) end = allcookies.length;    //If the end value is - 1, there is only one cookie in the cookie list
    var value = allcookies.substring(start,end); //Extract the value of the cookie
    return (value);              //Decoding it
  }else{ //Search failed, return empty string
    return "";
  }
}
function deleteCookie(name,path){  /**According to the key of the cookie, deleting the cookie is actually setting its invalidity**/
  var name = escape(name);
  var expires = new Date(0);
  path = path == "" ? "" : ";path=" + path;
  document.cookie = name + "="+ ";expires=" + expires.toUTCString() + path;
}
/**Implement the function to save the user's login information to the cookie. When the login page is opened, the cookie is queried**/
window.onload = function(){
  var userNameValue = getCookieValue("userName");
  document.getElementById("txtUserName").value = userNameValue;
  var userPassValue = getCookieValue("userPass");
  document.getElementById("txtUserPass").value = userPassValue;
}
function userLogin(){  /**User login, in which it is necessary to determine whether to choose to remember password**/
  //Check it out
  var userName = document.getElementById("txtUserName").value;
  if(userName == ''){
    alert("Please enter a user name.");
    return;
  }
  var userPass = document.getElementById("txtUserPass").value;
  if(userPass == ''){
    alert("Please input a password.");
    return;
  }
  var objChk = document.getElementById("chkRememberPass");
  if(objChk.checked){
    //Add cookie
    addCookie("userName",userName,7,"/");
    addCookie("userPass",userPass,7,"/");
    alert("Remember your password to log in.");
    window.location.href = "http://www.baidu.com";
  }else{
    alert("Log in without a password.");
    window.location.href = "http://www.baidu.com";
  }
}
</script>
</head>
<body>
<center>
  <table width="400px" height="180px" cellpadding="0" cellspacing="0" border="1" style="margin-top:100px;">
    <tr>
      <td align="center" colspan="2">Welcome to use XXX management system</td>
    </tr>
    <tr>
      <td align="right">
        <label>User name:</label>
      </td>
      <td align="left">
        <input type="text" id="txtUserName" name="txtUserName" style="width:160px; margin-left:10px;" />
      </td>
    </tr>
    <tr>
      <td align="right">
        <label>Password:</label>
      </td>
      <td align="left">
        <input type="password" id="txtUserPass" name="txtUserPass" style="width:160px; margin-left:10px;" />
      </td>
    </tr>
    <tr>
      <td align="center" colspan="2">
        <span style="font-size:12px; color:blue; vertical-align:middle;">Remember password or not</span>
        <input type="checkbox" id="chkRememberPass" name="chkRememberPass" style="vertical-align:middle;" />
      </td>
    </tr>
    <tr>
      <td align="center" colspan="2">
        <input type="submit" id="subLogin" name="subLogin" value="Sign in" onclick="userLogin()"/>
        <input type="reset" id="resetLogin" name="resetLogin" value="Reset" />
      </td>
    </tr>
  </table>
</center>
</body>
</html>
Published 17 original articles, won praise and 342 visitors
Private letter follow

Topics: Javascript Session Web Development