JAVASCRIPT COOKIES
- Cookies are pieces of information exchanged between the server and the client.
- It saves the user’s information on websites; in other words, it is a piece of data stored on the computer.
The following items are included in this blog:
- Why do we require them?
- How to make/use them
- There are five variable fields.
- What does javascript do with cookies?
- An example of how to apply them
Why do we require cookies?
- The HTTP protocol is used to communicate between a web browser and a server. However, after transmitting the information to the browser, the server never keeps it.
- The information may be needed in the future for some vital purpose.
Here how do cookies come??
- When we employ cookies, the browser does not have to contact with the servers every time it requires information.
- Instead, cookies are used to save information on the user’s computer so that it may be accessed from there.
HOW TO USE COOKIES?
- With the assistance of a document.cookie feature Javascript has the ability to read, write, and create cookies.
What is the syntax for making a cookie?
document.cookie = “name=xyz”;
5 fields with variable values
Based on a list of 5 changeable fields, each cookie can contain 5 variable path names or domains to a specific website.
The mentioned variable fields are listed below.
- Expires → It shows the date cookie will expire. If it is blank, whenever the user will visit the page it will be expired
- Domain → It displays the domain name of the site.
- Path → The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page.
- Secure → If this field contains the word “secure”, then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.
- Name=Value → Cookies are set and retrieved in the form of key-value pairs
What can javascript do with cookies?
Javascript can do a variety of things with cookies. Among them are:
- It is capable of reading cookies.
- It is capable of updating a cookie.
- It has the ability to remove cookies.
- It has the ability to check the cookie.
Let’s look at some examples of how we may write a javascript function to check the cookie.
function checkCookies(){ let cookie = getCookie("emp"); if(cookie != ""){ alert("cookie is "+cookie); }else{ cookie=prompt("can you enter your name?"); if(cookie != "" && cookie!=null){ setCookies("emp", cookie, 2); } } }