What is JavaScript Cookies? Cookies are small text files that store on your browser/local hard drive. Cookies are created when you visit websites that use cookies to store information. Websites often use cookies to personalize the user name and much more details are remembering. It effect is you can not required to write in second time this information only confirm to the user.
- Each website have capable to store up to 20 cookies. Storage space is 4KB (four kilobytes) per website.
- Latest browsers are capable to store at least 300 cookies. of four kilobytes (4 kb) per server or domain.
- Website can set and read only its own website cookies. Its means don't read other website cookies.
- Cookies can't accessed by any other computer except your own computer which is created cookies.
How cookies work
A cookies name with value pair containing the actual value data.
Also have expiry date of this cookies after which is not valid.
Website path of the server which should set and send to your own computer.
How to Creating Cookies in JavaScript?
You can see your local hard drive cookies folder following cookies file are created. You can read this code easily.
document.cookie = "MyMessage=JavaScript Cookies store in the local drive; expires=Sat, 20 Jun 2020 12:00:00 UTC; path=/temp";
Example
<script type="text/javascript">
function SetCookie(){
if( document.mycookies.visitor.value == "" ){
alert("Enter Your Name...");
return;
}
cookie_visitor_value = escape(document.mycookies.visitor.value) + ";";
document.cookie="name=" + cookie_visitor_value;
alert("Set Cookies : " + "Visitor Name=" + cookie_visitor_value );
}
</script>
<form name="mycookies" action="">
Enter Your Name: <input type="text" name="visitor"/>
<input type="button" value="Set Cookie" onclick="SetCookie();"/>
</form>
Example Result
How to Get/Read Cookies in JavaScript?
You can simply reference to the read cookies message.
document.write(document.cookie);
Example
<script type="text/javascript">
function ReadCookies() {
var get_cookies = document.cookie;
alert("All Cookies: " + get_cookies );
// Get all the cookies pairs store in array
cookie_array = get_cookies.split(";");
// Need for get cookies key with value
for(var i=0; i<1; i++){
name = cookie_array[i].split("=")[0];
value = cookie_array[i].split("=")[1];
alert("Cookies Key is: " + name + " and Key Value is: " + value);
}
}
</script>
<form name="read_cookies" action="">
<input type="button" value="Get Cookie" onclick="ReadCookies()"/>
</form>
Example Result
Deleting Cookies in JavaScript?
For deleting a cookie, you have to use the same code you used to create and set the expiry date in the past date/time.
document.cookie = "MyMessage=JavaScript Cookies store in the local drive; expires=Sat, 20 Jun 2020 12:00:00 UTC; path=/temp";