search
HomeWeb Front-endJS TutorialJavaScript implementation method of reading and writing cookies

In this article, we will first learn about cookies, and then share with you the implementation method of reading and writing cookies in JavaScript. I hope it can help you.

First of all, let us briefly understand cookies.
In the process of making web pages, we often need to transfer information from one page to another. At this time, we need to use cookies in JavaScript mechanism. Simply put, cookies provide a convenient way to save small amounts of data on the user's computer and obtain it remotely, allowing websites to save details such as the user's habit settings or the time of the last visit to the website. The cookie itself is a short piece of information that can be saved on the user's computer by the page and then read by other pages. Cookies are generally set to expire after a certain period of time.
 Of course, cookies also have limitations: browsers have limits on the number of cookies that can be saved, usually a few hundred or more. Under normal circumstances, 20 cookies are allowed per domain name, and each domain can save up to 4KB of cookies. In addition to the problems that may be caused by size restrictions, there are also many reasons that may cause cookies on the hard disk to disappear, such as reaching the expiration date. Or the user cleared the cookie information, or switched to another browser. Therefore, cookies are not suitable for storing important data. When writing code, you must also consider how to handle cookie acquisition exceptions.
 In JavaScript, use the cookie attribute of the document object to store and retrieve cookies. Usually, the information in document.cookie is a string consisting of pairs of names and values. The form of each pair of data is:

name=value;

 Below we will use a simple example to show how to read and write cookies in JavaScript.
 First is createCookie.html, which will be created in this page A cookie, the complete code is as follows:


    <title>createCookie</title>
    <script>
        function createCookie(){
            //get name and password
            var name = document.getElementById("name").value;
            var pwd = document.getElementById("pwd").value;
            //create cookie
            document.cookie = name+&#39;|&#39;+pwd;
            //go to showCookie.html page
            window.location.href = "showCookie.html";
        }
    </script>


    Userame:  <input><br><br>
    Password:  <input><br><br>
    <button>Submit

</button>

The screenshot of the page is as follows:

JavaScript implementation method of reading and writing cookies

Click the submit button and a cookie will be created. cookie, the Username and Password information is saved in this cookie, and it will jump to the showCookie.html page. Among them, the complete code of the showCookie.html page is as follows:


    <title>showCookie</title>
    <script>
        function showCookie(){
            //document.cookie is a string, using split() function to get cookie date in array form 
            var arr = document.cookie.split(&#39;|&#39;);
            //processing data in cookie
            var cookie_info = &#39;Data in cookie:<br>username is:  &#39;+arr[0]+"<br>password is:  "+arr[1]+&#39;<br>&#39;;
            //set content of element of id "res"
            document.getElementById("res").innerHTML = cookie_info;
        }
    </script>


    <button>Show Cookie</button>
    <p></p>

The screenshot of the page is as follows:

JavaScript implementation method of reading and writing cookies

Click the show Cookie button to display the information in the cookie.
 Next, we will run this program locally and on the server, and run this program on IE browser and Chrome browser respectively to see how the cookie works.
  First we run this program locally, and we put the above two files in the E drive. First run it on the IE browser, enter the information on the createCookie.html page, and click the submit button. The screenshot is as follows:

JavaScript implementation method of reading and writing cookies

Jump to showCookie .html page, click the show Cookie button, the page screenshot is as follows:

JavaScript implementation method of reading and writing cookies

Cookies run normally in the IE browser in the local environment.
 Next, let’s take a look at the operation in the Chrome browser. First, open the createCookie.html page in the Chrome browser, enter the information, and click the submit button. The screenshot is as follows:

JavaScript implementation method of reading and writing cookies

After jumping to the showCookie.html page, click the show Cookie button. The screenshot of the page is as follows:

JavaScript implementation method of reading and writing cookies

## The same program, this time the cookie failed to run in the Chrome browser.

 Then let us run this program in the server. We need to use xampp and open the Apache server. Place the above two html files in the htdocs folder under the xampp installation folder (for specific operation methods, please refer to this article Blog: Using AJAX with JavaScript (for beginners)). We now run the program in the IE browser and enter the URL in the IE browser: http://localhost/createCookie...:

JavaScript implementation method of reading and writing cookies

Click the Submit button, jump to the showCookie.html page, and click the show Cookie button. The screenshot is as follows:

JavaScript implementation method of reading and writing cookies

 Then we enter it in the Chrome browser URL: http://localhost/createCookie...:

JavaScript implementation method of reading and writing cookies

Click the Submit button, jump to the showCookie.html page, and click show Cookie button, the screenshot is as follows:

JavaScript implementation method of reading and writing cookies

#This time in the server environment, the cookies of IE browser and Chrome browser are running normally!

Related recommendations:

How to implement jQuery encrypted cookies

Detailed explanation of JavaScript to obtain cookies and delete cookies

How to use cookies with jQuery

The above is the detailed content of JavaScript implementation method of reading and writing cookies. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools