Ramble about cookies in JavaScript

Source: Internet
Author: User
Tags setcookie ssl connection

What is a cookie? In short, a cookie is a piece of text that the Web server stores on our computer (typically less than 4KB in size) to identify and record the user's personal information. The HTTP protocol is a transport protocol that does not have a "state", that is, the server does not recognize any two accesses for the same source, so that the user information cannot be judged and thus cannot be personalized for a particular user. In order to solve this problem, cookie technology emerged.

How exactly does a cookie work? For a chestnut, when we log in once on the webpage, the next time we log in again, we will find that our user name (and possibly the password) has already appeared in the input box without having to manually enter it again, which is where the cookie is working. When you first log in to a Web site, the server-side executable (PHP, ASP, and so on) or client script (this lead: JavaScript) will record some of our operations (such as personalization) and store them in a cookie. The next time you visit this page, the browser will find the address locally before sending an HTTP request to the server, whether there is a cookie or, if so, adding the cookie information to the requested header. When the server receives the request, it parses the cookie, interprets the information in the cookie into the HTML page to be sent, and then sends the Web file to the client browser.

A complete cookie contains the following fields (each of which consists of a name-value pair):

Document.cookie = "Name=value;expires=datestring;domain=www.example.com;path=/pathstring/;secure";
    1. Name: By definition, is a cookie.
    2. The value of Value:cookie, which is URI-encoded as name.
    3. Expires: The expiration time, after expires the specified time, this cookie will be deleted, if not specified, then it will be deleted when the browser is closed.
    4. Domain: field, which is the name of the domain in which the cookie should be sent to when the site is visited.
    5. The path under Path:domain, if a path is specified, the cookie is accessible only under the current path and cannot be accessed under other paths in the domain.
    6. Secure: Security flag that states that secure cookies are sent to the server only if the SSL connection (that is, the HTTPs://Header link).

So how do you manipulate cookies in JavaScript? JavaScript reads and sets cookies by document.cookie this property. The following are examples of how to set, read, and delete cookies, respectively.

First, set a cookie

        /*The following code shows how to set a cookie through JavaScript*/        functionSetcookie (name,value,days,path,domain,secure) {//reads the name and value of the cookie to be set from the parameter and encodes the URI            varCookietext = encodeURIComponent (name) + "=" +encodeURIComponent (value); //set the expiration time of the cookie, set according to the number of days that the external input            varExp =NewDate (); Exp.settime (Exp.gettime ()+ days*24*60*60*1000); Cookietext+ = "; expires=" +exp.togmtstring (); //if path, domain, and secure are not empty in the parameters, the fields on the Cookietext infix are sequentially            if(path) {Cookietext+ = ";p ath=" +path; }            if(domain) {cookietext+ = ";d omain=" +domain; }            if(Secure) {Cookietext+ = "; secure"; }            //set the page's cookie to the value of CookietextDocument.cookie =Cookietext; }

Second, read the cookie

        /*The following code shows how to read a page cookie through JavaScript. */        functionGetCookie (str) {//read the cookie to get from the parameter str            varname = encodeURIComponent (str) + "="; //read the location of the cookie in the Document.cookie string            varStart =document.cookie.indexOf (name); //returns False if it is not read            if(Start = =-1){                return false; }            /*because each cookie field is ";" End of the (except the last one), so we start from the position to find ";" The first occurrence of this position is the end of this cookie.*/            varEnd = Document.cookie.indexOf (";", start); if(end = =-1) {End=document.cookie.length; }            /*start + name.length just reaches the "=" position in this cookie, so the position behind until end is the value string*/            varValue = decodeURIComponent (document.cookie.substring (start +name.length,end)); returnvalue; }

Third, delete cookies

        /*         The following code shows how to delete a cookie by using JavaScript Delete cookie        is very simple, when the expiration time of the cookie is set to the current time,        it is immediately deleted. Here's the front Setcookie function         *          /function Removecookie (name,path,domain,secure) {            return setcookie (name, "",New Date (0), path,domain,secure);        }

This is the whole process of using JavaScript to manipulate cookies. Next, we use JavaScript to complete a small example. This example will prompt the user when the page was last opened every time the user opens it. (Note: Please select the Firefox browser to test this example, because Google Chrome does not support setting cookies under the file:///protocol, if you must use chrome, you must build php+mysql+ Apache's localhost environment) to implement this feature, we set up a cookie named Lasttime. Each time the user is about to close, call the window's onbeforeunload event to first delete the Lasttime cookie (because it records the last logon time set), and then set the current time to Lasttime value. The next time the user opens the page, we read the value of the lasttime from the Document.cookie and then use the DOM method to display the information on the screen. Here is the specific code:

<!DOCTYPE HTML><HTMLLang= "ZH-CN"><Head>    <MetaCharSet= "Utf-8">    <title>Cookies</title></Head><Body>    <Script>window.onload= function(){        //after the page is loaded, read the cookie named Lasttime and output it to the screen            if(document.cookie) {varWelcome=GetCookie ("Lasttime"); document.write ("Last time visit:" +welcome); }} window.onbeforeunload= function(){        //before the page closes, delete the last value before setting the new value            if(Document.cookie) {Removecookie ("Lasttime","",0); }            var Now= NewDate (); varv=now.tolocalestring (); Setcookie ("Lasttime", V, -); }    </Script></Body></HTML>

The results of the operation are as follows:

Reference documents:

1. Gaohong and so on. "JavaScript from Beginner to Mastery". Mechanical Industry Press

2.Nicholas C. Zakas. Advanced programming of JavaScript (Chinese version III). People's post and telecommunications publishing house

Ramble about cookies in JavaScript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.