Cookies in JavaScript
Cookies in JavaScript
Ex:-
document.cookie = “username=geeky”;
document.cookie = “username=geeky; expires=Monday, 3-Sep-2018 09:00:00 UTC”;
document.cookie = “username=geeky; max-age=”+60*60*24*10;
Note - name-value pair must not contain any whitespace character, Commas or semicolons.
Ex: - username=geeky shows;
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 cookie. 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:-
document.cookie = “username=geeky; max-age=" + 60 * 60 * 24 * 10;
document.cookie = “username=geeky; max-age=" + 60 * 60 * 24 * 10 + “; path=/”;
expires
It is used to create persistent cookie.
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.
alert(document.cookie);
Deleting Cookies
A cookie is deleted by setting a cookie with the same name (and domain and path, if
they were set) with an expiration date in the past and if using max-age then must set a
negative value.
Ex: -
document.cookie = “username=geeky; expires=Monday, 3-Sep-2018 09:00:00 UTC”;
document.cookie = “username=geeky; expires=Thu, 01-Jan-1970 00:00:01 GMT”;
document.cookie = “username”;
document.cookie = “username; expires=Thu, 01-Jan-1970 00:00:01 GMT”;
Updating Cookies
A cookie is possible to update by setting new value to a cookie
with the same name.
Ex: -
document.cookie = “username=geeky”;
document.cookie = “username=shows”;
Cookies Security Issues
• Can misuse Client Details
• Can track User
• Client Can Delete Cookies
• Client can Manipulate Cookies
Cookies Limitation
• Support HTML4 / HTML 5
• Each cookie can contain 4kb Data
• Cookies can be stored in Browser and server
• It is sent with each request