Javascript create, read, and delete cookies (ok)
Create a cookie. The window object has the document as a child object, and the document object has the cookie properties. You just have to set some value to tthe widown.document.cookie to create a cookie.
/**
* Set a cookie
* @param {String} cname, cookie name
* @param {String} cvalue, cookie value
* @param {Int} exdays, number of days before the cookie expires
*/
function setCookie(cname,cvalue,exdays) {
var d = new Date(); //Create an date object
d.setTime(d.getTime() + (exdays*1000*60*60*24)); //Set the time to exdays from the current date in milliseconds. 1000 milliseonds = 1 second
var expires = "expires=" + d.toGMTString(); //Compose the expirartion date
window.document.cookie = cname+"="+cvalue+"; "+expires;//Set the cookie with value and the expiration date
}
Read a cookie. As long as you know the cookie name, you can loop through window.document.cookies to get the cookie value.
/**
* Get a cookie
* @param {String} cname, cookie name
* @return {String} String, cookie value
*/
function getCookie(cname) {
var name = cname + "="; //Create the cookie name variable with cookie name concatenate with = sign
var cArr = window.document.cookie.split(';'); //Create cookie array by split the cookie by ';'
//Loop through the cookies and return the cooki value if it find the cookie name
for(var i=0; i<cArr.length; i++) {
var c = cArr[i].trim();
//If the name is the cookie string at position 0, we found the cookie and return the cookie value
if (c.indexOf(name) == 0)
return c.substring(name.length, c.length);
}
//If we get to this point, that means the cookie wasn't find in the look, we return an empty string.
return "";
}
Delete a cookie. To delete a cookie works similar to set or create a cookie. The only difference is that you set the expiration date of the cookie in the past instead of future.
/**
* Delete a cookie
* @param {String} cname, cookie name
*/
function deleteCookie(cname) {
var d = new Date(); //Create an date object
d.setTime(d.getTime() - (1000*60*60*24)); //Set the time to the past. 1000 milliseonds = 1 second
var expires = "expires=" + d.toGMTString(); //Compose the expirartion date
window.document.cookie = cname+"="+"; "+expires;//Set the cookie with name and the expiration date
}
These are some use cases of the above 3 functions for create, read and delete cookies.
/**
* Check if there is a vistorname cookie.
* If yes, display welcome message.
* If No, prompt the vistor for a name, and set the vistorname cookie.
*/
function checkCookie() {
//deleteCookie('vistorname');
var vistor=getCookie("vistorname");
if (vistor != "") {
var welcome_msg = window.document.getElementById('welcome-msg');
welcome_msg.innerHTML="Welcome "+vistor;
} else {
vistor = prompt("What is your name?","");
if (vistor != "" && vistor != null) {
setCookie("vistorname", vistor, 30);
}
}
}
/**
* Set a cooke and reload the page when the create cookie button is clicked
*/
function setACookie(){
var cname = window.document.getElementById('cname').value; //Get the cookie name from the cname input element
var cvalue = window.document.getElementById('cvalue').value;//Get the cookie value from the cvalue input element
var exdays = window.document.getElementById('exdays').value;//Get the expiration days from the exdays input element
setCookie(cname, cvalue, exdays);//Call the setCookie to create the cookie
window.location.reload();//Reload the page
}
/**
* Delete a cookie and reload the page when the delete cookie button is clicked
*/
function deleteACookie(){
var cname = window.document.getElementById('cname').value;//Get the cookie name from the cname input element
deleteCookie(cname);//Call the deleteCookie to delete the cookie
window.location.reload();//Reload the page
}
/**
* Display all the cookies
*/
function disPlayAllCookies()
{
var cookieDiv = window.document.getElementById('cookies');//Get the cookies div element
var cArr = window.document.cookie.split(';'); //Create cookie array by split the cookie by ';'
//Loop through all the cookies and display them with cookie name = cookie value
for(var i=0; i<cArr.length; i++)
{
var pElm = window.document.createElement("p");//Create a p element to hold the cookie name and cookie value
pElm.innerHTML=cArr[i].trim();//Put the cookie name and cookie value in the p elment
cookieDiv.appendChild(pElm);//Append the p to the cookies div element
}
}
All together. The index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jscookie.js"></script>
<style>
label
{
display:inline-block;
width:100px;
text-align:right;
}
</style>
</head>
<body onload="checkCookie();disPlayAllCookies();">
<div id='welcome-msg'></div>
<div name="cookieForm" id="cookieForm">
<label>Cookie Name</label><input id="cname" type="text"/><br>
<label>Cookie Value</label><input id="cvalue" type="text"/><br>
<label>Expiraton days</label><input id="exdays"type="number" min="1"/><br>
<button id="createBtn" onClick="setACookie();">Create Cookie</button>
<button id="deleteBtn" onClick="deleteACookie();">Delete Cookie</button>
</div>
<div id="cookies">
<h2>Cookies</h2>
</div>
</body>
</html>
The jscookie.js
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*1000*60*60*24));
var expires = "expires=" + d.toGMTString();
window.document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname) {
var name = cname + "=";
var cArr = window.document.cookie.split(';');
for(var i=0; i<cArr.length; i++) {
var c = cArr[i].trim();
if (c.indexOf(name) == 0)
return c.substring(name.length, c.length);
}
return "";
}
function deleteCookie(cname) {
var d = new Date();
d.setTime(d.getTime() - (1000*60*60*24));
var expires = "expires=" + d.toGMTString();
window.document.cookie = cname+"="+"; "+expires;
}
function checkCookie() {
var vistor=getCookie("vistorname");
if (vistor != "") {
var welcome_msg = window.document.getElementById('welcome-msg');
welcome_msg.innerHTML="Welcome "+vistor;
} else {
vistor = prompt("What is your name?","");
if (vistor != "" && vistor != null) {
setCookie("vistorname", vistor, 30);
}
}
}
function setACookie(){
var cname = window.document.getElementById('cname').value;
var cvalue = window.document.getElementById('cvalue').value;
var exdays = window.document.getElementById('exdays').value;
setCookie(cname, cvalue, exdays);
window.location.reload();
}
function deleteACookie(){
var cname = window.document.getElementById('cname').value;
deleteCookie(cname);
window.location.reload();
}
function disPlayAllCookies()
{
var cookieDiv = window.document.getElementById('cookies');
var cArr = window.document.cookie.split(';');
for(var i=0; i<cArr.length; i++)
{
var pElm = window.document.createElement("p");
pElm.innerHTML=cArr[i].trim();
cookieDiv.appendChild(pElm);
}
}
PreviousSử dụng window.addEventListener để resize và responsive <3NextTự động submit bằng javscript :))) (ok)
Last updated