By Nick Major
Translation: Crazy geek
Original text: coderrocketfuel.com/article/how…
Reproduced without permission
introduce
The Web server and HTTP server are stateless, so when the Web server sends the Web page to the browser, the connection is broken and the server forgets everything relevant to the user.
So how do browsers and Web servers remember user information? Cookies were invented to solve this problem.
When a user visits a Web page, their name, unique ID, or any other information can be stored in a browser cookie. The cookie will remember the user’s name or unique ID the next time they come back to the page.
A Cookie is just a small text file stored in a computer’s browser. They contain the following data:
- Saves a name-value pair of data
- When the date expires, the cookie becomes invalid
- The domain and path to the server to which it should be sent
Cookies also have some limitations worth mentioning:
- The maximum size of each cookie is 4096 bytes
- Maximum of 20 cookies per field (slightly different for each browser)
- Cookies are specific to their own domain names (websites cannot read cookies from other domains, only their own)
- The size limit applies to the entire cookie, not just its value
In the browser, cookies are exposed as document.cookies through the document object.
In the following sections, we’ll show you how to set, get, update, and delete Cookie data in a browser using JavaScript.
Let’s get started!
directory
- Create Cookies
- Read Cookies
- Update Cookies
- Delete Cookies
Create Cookies
Setting cookies in your browser with JavaScript is easy! I’ll show you below.
Set the Cookie
Here is the execution code to create a new cookie in JavaScript in the browser:
document.cookie = "userId=nick123"
Copy the code
After running the code, open your browser and you should find the cookie in the developer tools Application (Safari or Chrome) or Storage (Firefox).
The cookie expiration time is set
You can also add an expiration time (UTC) to the Cookie to tell the browser when it should be deleted:
document.cookie = "userId=nick123; expires=Wed, 15 Jan 2020 12:00:00 UTC"
Copy the code
Set a Cookie path
You can also tell the browser where the cookie belongs (the default is the current page path) :
document.cookie = "userId=nick123; expires=Wed, 15 Jan 2020 12:00:00 UTC; path=/user"
Copy the code
Set the cookie domain
The last piece of data we’ll cover is the domain to which the cookie belongs (default is the current domain) :
document.cookie = "userId=nick123; expires=Wed, 15 Jan 2020 12:00:00 UTC; path=/user; domain=mysite.com"
Copy the code
Read Cookies
Using the document.cookie object, it is also very simple to read cookies in JavaScript:
Read all cookies from a single page
Get all cookies for a single page as a string, separated by a semicolon:
const cookies = document.cookie
Copy the code
Reads cookies with a specific name
To access a cookie with a specific name, we need to get all the cookies on the page and parse the string, then look for a match for the cookie name we want to look for.
Here’s a function that uses regular expressions to do this:
function getCookieValue(name) {
let result = document.cookie.match("(^ | [^;] +)\\s*" + name + "\\s*=\\s*([^;] +)")
return result ? result.pop() : ""
}
Copy the code
You use the function like this:
getCookieValue("userId") //returns nick123
Copy the code
This returns the string value corresponding to the name argument supplied to the function.
If you haven’t mastered regular expressions yet, there’s another function that does the same thing:
function getCookieValue(name) {
const nameString = name + "="
const value = document.cookie.split(";").filter(item= > {
return item.includes(nameString)
})
if (value.length) {
return value[0].substring(nameString.length, value[0].length)
} else {
return ""}}Copy the code
Use this function in the same way:
getCookieValue("userId") //returns nick123
Copy the code
Update Cookies
You can change the cookie’s value by overwriting it with a new value by creating it.
You can override the cookie “userId” created earlier in this article with this code:
document.cookie = "userId=new_value"
Copy the code
When you run the getCookieValue function again, the new value is returned:
getCookieValue("userId") //returns new_value
Copy the code
Delete Cookies
You can delete cookies by giving them a null value and setting their expiration date to any time in the past.
If we want to delete the cookie “userId” from the previous example, do the following:
document.cookie = "userId=; expires=Thu, 01 Jan 1970 00:00:00 UTC;"
Copy the code
Easy, right?
conclusion
A: congratulations! Now you know how to set, read, update, and delete cookies with JavaScript! Hopefully this will help you with your coding.