
Javascript set cookie(read, modify and delete)
In the process of website development, using javascript to set cookies is not only often used, but also can reduce the burden on the server, and sometimes it is necessary. For example, the menu on the left side of the background management system is to use javascript to operate cookies.
Javascript operation cookies include setting, reading, modifying and deleting, they have no existing methods, you need to write your own code and encapsulate it into a method; For convenience, they have been shared below.
1. Javascript set cookie
function setCookie(cookieName, cookieValue, expireHours){
var CookieStr = cookieName + "=" + escape(cookieValue);
//Without setting the expiration time, the cookie disappears automatically when the browser is closed
if(expireHours > 0){
var date = new Date();
var ms = expireHours * 3600 * 1000;
date.setTime(date.getTime() + ms);
str += "; expires=" + date.toGMTString();
}
document.cookie = CookieStr;
}
Call: setCookie("myCookie","menu1",2);
2. Javascript read cookie(i.e. Javascript get cookie)
function getCookie(cookieName){
var cookieStr = document.cookie.split(";");
for (var i = 0; i < cookieStr.length; i++){
var val = cookieStr[i].split("=");
if (escape(cookieName) == val[0])
return unescape(val[1]);
}
return null;
}
Call: getCookie("myCookie");
3. Javascript delete cookie
function DeleteCookie(CookName){
var date = new Date();
date.setTime(date.getTime() - 10000);
var val = getCookie(cookieName);
if(val != null)
document.cookie= cookieName + "=;expires=" + date.toGMTString();
}
Call: DeleteCookie("myCookie");
-
Related Reading
- Javascript multidimensional array (create, add and r
- Remove text after clicking in the textbox and then d
- Javascript get referrer url(previous page url), curr
- Javascript get current url, domain from url, relativ
- Javascript convert hex to decimal, binary to hex, oc
- Javascript delay loading images to improve web page
- Remove html element javascript by their parent or cl
- Javascript split usage and examples, with splitting
- Javascript get all input elements in form and all im
- Javascript sets the element height that cannot be au
- Javascript create element(div,li,img,span) dynamical
- Javascript click child element to add onclick to par