JavaScript 和cookie

In Web terminology, a cookie is a small piece of information. When a user visits a Web server for the first time, the server sends this information to the browser. Every time the user visits this Web site in the future, the Web server can identify the user through cookies. The browser saves the cookie (which contains information about the visitor) as a plain text file on the computer's hard drive.
If your site requires registration, you can use cookies to save the visitor's username and password on their hard drive so that they don't need to enter the username and password every time they visit. You can track which parts of the site the user has visited, and count the number of times the user has visited.
There are many common misunderstandings about cookies, so be sure to know what cookies cannot do: you cannot get any real information about the user, such as their email address; you cannot use cookies to view the content on the user’s hard drive; cookies cannot transmit computer viruses . A cookie is just a simple text file on the user's hard drive, and JavaScript developers can store some
information in it, nothing more.
** A cookie always contains the address of the server that sent it. The essence behind cookie technology is "identification". **It can be regarded as the Caller ID on the Web, but there are various changes in form-each Web site that uses cookies grants some form of personalized ID to the user's browser, so that the user will visit the next time This site can recognize him. When the user visits the Web server that previously passed the cookie to him again, the server can query the browser to find out whether the user has its cookie. If it is, the server can obtain the information stored in the originally passed cookie. Remember, the cookie only identifies the computer used, not the person using this computer.

You can set multiple cookies on one page, the format is as follows:
"cookieName1=cookieValue1;expires=expirationDateGMT1;path=sitePath1;domain=siteDomain1";
"cookieName2=cookieValue2;expires=expirationDateGMT2;path=sitePath2;domain=siteDomain2"
Similarly, Only the name and value pair are required fields.
The split("; ") command separates multiple cookie records into an array, and each cookie is numbered from zero. Note that there is a space after the semicolon in this command. cookieArray[0] is the first cookie in multiple cookie records, cookieArray[1] is the next cookie, and so on

The first cookie page:

<!DOCTYPE html>
<html>
<head>
<title>I know your name!</title>
<script src="script01.js"></script>
</head>
<body>
<h1 id="nameField">&nbsp;</h1>
</body>
</html>

Use this script to set browser cookies:

window.addEventListener("load",nameFieldInit,false);
function nameFieldInit() {
    
    
var userName = "";
if (document.cookie != "") {
    
    
userName = document.cookie.split("=")[1];
}
document.getElementById("nameField").value = userName;
document.getElementById("nameField").onblur = setCookie;
document.getElementById("cookieForm").onsubmit = setCookie;
}
function setCookie() {
    
    
var expireDate = new Date();
expireDate.setMonth(expireDate.getMonth()+6);
var userName = document.getElementById("nameField").value;
document.cookie = "userName=" + userName + ";expires=" + expireDate.toGMTString();
document.getElementById("nameField").blur();
return false;
}

Effect:
Insert picture description here
Although it is not visible on the surface, the content of the form text field has been written into the cookie
2.
var userName = "";
Next, initialize the variable userName with a null value.
3.
if (document.cookie != “”) { userName = document.cookie.split("=")[1]; This conditional test checks whether the document.cookie object does not contain null values. The split("=") method divides the cookie into an array. The first element (cookieField[0]) in the array is the name of the cookie, and the second element (cookieField[1]) is the value of the cookie. Note that this array can be any variable that stores the cookie field. Here, the value returned by document.cookie.split("=")[1] (that is, the value of the cookie) is assigned to userName. 4. document.getElementById("nameField").value = userName; If a user name is stored in the cookie file, then set getElementById ("nameField") when the page loads. value will put the user name in the text field. 5. document.getElementById("nameField").onblur = setCookie; document.getElementById("cookieForm").onsubmit = setCookie;






In the first line, when the user leaves this text field, the onblur event handler will call the setCookie() function. In the second line, the onsubmit event handler of the form does the same thing. If the user presses Enter after entering the name, IE will not trigger the onblur handler (for some reason). The onsubmit handler is added to adapt to all browsers.
6. function setCookie() { Now create a new function setCookie(). 7. var expireDate = new Date(); Get the current date and assign it to the new variable expireDate. 8. expireDate.setMonth(expireDate.getMonth()+6); This line takes out the month part of expireDate, adds 6 to the month, and then sets the month part of expireDate to a new value. In other words, it sets the expiration date of the cookie to 6 months after the cookie is created. 9. var userName = document.getElementById("nameField").value; This line creates a new variable userName and assigns the value entered by the user in the text field to it. userName variable must be created twice (each time in a different function), that is, it can be used in each function, because it is not a global variable, but is not expected to function across maintain its value - in every Its value in each function is new. 10. document.cookie = "userName=" + userName + ";expires=" + expireDate.toGMTString();











This is the place to write cookies. Remember, cookie is just a text string, so you can use any text string manipulation to create a cookie , such as using a plus sign to connect strings. We set document.cookie to include the username and cookie expiration date. The toGMTString() method converts the expireDate Date object into a text string so that it can be written into the cookie.

A cookie can only be read by the server that originally wrote it. The cookie mechanism inside the browser does not allow you to read or write cookies written by others. You can only access your own cookies.

Example:

Read all cookies from your server

Write a script to read all cookies from your server and display their names and values. If there are no cookies, the script will display There are no cookies here. If there are cookies, display the content of each cookie on a separate line (

window.addEventListener("load",showCookies,false);
function showCookies() {
    
    
var outMsg = "";
if (document.cookie == "") {
    
    
outMsg = "There are no cookies here";
}
else {
    
    
var thisCookie = document.cookie.split("; ");
for (var i=0; i<thisCookie.length;i++) {
    
    
outMsg += "Cookie name is '" + thisCookie[i].split("=")[0];
outMsg += "', and the value is '" + thisCookie[i].split("=") [1] + "'<br>";
}
}
document.getElementById("cookieData").innerHTML = outMsg;
}

Record the number of visits in a cookie

window.addEventListener("load",initPage,false);
function initPage() {
    
    
var expireDate = new Date();
expireDate.setMonth(expireDate.getMonth()+6);
var hitCt = parseInt(cookieVal("pageHit"));
/*字符串pageHit 是这个cookie 的名称。这一行从cookieVal()获得cookie 的名字,并且用parseInt()方法将它转换为数字,然后将结果存储进变量hitCt。parseInt()方法将一个字符串(cookie 中的值)转换为数字(用作计数器的值)。*/
hitCt++;/*现在将hitCt 的值加1,从而递增计数器。*/
document.cookie = "pageHit=" + hitCt + ";expires=" + expireDate.toGMTString();/*这行代码将更新后的信息写回cookie。写入的内容是一个文本字符串,其中包括字符串"pageHit="、递增后的hitCt 值、";expires="和过期日期*/
document.getElementById("pageHits").innerHTML = "You have visited this page " + hitCt + " times.";
}
function cookieVal(cookieName) {
    
    
var thisCookie = document.cookie.split("; ");/*将变量thisCookie 设置为split("; ")方法生成的数组。*/
for (var i=0; i<thisCookie.length; i++) {
    
    
if (cookieName == thisCookie[i].split("=")[0]) {
    
    /*这个条件语句检查cookieName 是否与cookie 数组中的第i 个元素的名称相同。*/
return thisCookie[i].split("=")[1];
}
}
return 0;
}

var hitCt = parseInt(cookieVal(“pageHit”));

Delete cookie

One technique that works well is to set the expiration date of the cookie to a date in the past, which will cause the browser to delete it automatically

window.addEventListener("load",cookieDelete,false);
function cookieDelete() {
    
    
var cookieCt = 0;/*所以首先创建cookieCt 变量并且将它设置为零。*/
if (document.cookie != "" && confirm ("Do you want to delete the cookies?"))/*这个测试首先确保cookie 不包含空值,也就是说,存在一些cookie。如果测试表明cookie 是空的,那么脚本就不进行任何操作。第二部分让浏览器弹出一个确认对话框,其中显示函数调用中的文本。如果confirm()返回true,我们就知道用户希望删除他们的cookie,
 */
 {
    
    
var thisCookie = document.cookie.split("; ");
/*这一行用split("; ")方法将cookie 的内容分隔成数组,并且将这个数组赋值给变量thisCookie。*/
cookieCt = thisCookie.length;
/*我们现在知道将要删除多少个cookie,所以将这个值存储在cookieCt 中。*/
var expireDate = new Date();
expireDate.setDate(expireDate.getDate()-1);
/*这里创建一个新的日期对象expireDate,然后将它设置为当前日期减1——换句话说,就是昨天。*/
for (var i=0; i<cookieCt; i++) {
    
    
var cookieName = thisCookie[i].split("=")[0];
document.cookie = cookieName + "=;expires=" + expireDate.toGMTString();
/*这里将修改后的过期日期写回cookie 中。*/
}
}
document.getElementById("cookieData").innerHTML = "Number of cookies deleted: " + cookieCt;
/*将已经删除的cookie 数量写到HTML 文档中(*/
}

Guess you like

Origin blog.csdn.net/qq_41358574/article/details/112687966