How many create cookies in JavaScript?

JavaScript Cookies

Cookies are exposed as the cookie property of the Document object. This property is both readable and writeable.

You can see Cookies in Google Chrome by following chrome://settings/content/cookies

Creating Cookies

When you assign a string to document.cookie, the browser parses it as a cookie and adds it to its list of cookies. There are several parts to each cookies, many of them optional.

Syntax: –

document.cookie = “name=value”;
document.cookie = “name=value; expires=date; domain=domain; path=path; secure”;
document.cookie = “name=value; max-age=inSecond; domain=domain; path=path; secure”;

Ex:-

Creating Cookies

Optional Cookies Attribute:-

max-age
expires
domain
path
secure

Whenever you omit the optional cookie fields, the browser fills them in automatically with reasonable defaults.

max-age

It is used to create persistent cookies. It is supported by all modern browsers except IE.

Type of cookies: –

  • Session Cookies – Cookies that are set without the expires/max-age field are called session cookies. It is destroyed when the user quits the browser.
  • Persistent Cookies – The browser keeps it up until their expiration date is reached.

Ex:-

expires

It is used to create persistent cookies.

Type of cookies: –

  • Session Cookies – Cookies that are set without the expires/max-age field are called session cookies. It is destroyed when the user quits the browser.
  • Persistent Cookies – The browser keeps it up until their expiration date is reached.

Ex:-

document.cookie = “username=devops; expires=Monday, 3-Sep-2018 09:00:00 UTC”;

domain

It specifies the domain for which the cookie is valid. If not specified, this defaults to the host portion of the current document location. If a domain is specified, subdomains are always included.

Ex: –

path

Path can be / (root) or /mydir (directory). If not specified, defaults to the current path of the current document location, as well as its descendants.

Ex: – document.cookie = “username=devops; path=/”;

Ex: – document.cookie = “username=devops; path=/home”;

secure

Cookie to only be transmitted over secure protocol as https. Before Chrome 52, this flag could appear with cookies from http domains.

Ex: – document.cookie = “username=devops; secure”;

Tagged : / / / / /
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x