JS sets cookies and deletes cookies

Keywords: Web Development Javascript Google

There are many ways to set cookie s in js.
The first one is: (This is the code of w3c official website)

     <script>
//Set cookie
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}
//Get cookie
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(";");
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==" ") c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return "";
}
//Clear cookie  
function clearCookie(name) {  
    setCookie(name, "", -1);  
}  
function checkCookie() {
    var user = getCookie("username");
    if (user != "") {
        alert("Welcome again " + user);
    } else {
        user = prompt("Please enter your name:", "");
        if (user != "" && user != null) {
            setCookie("username", user, 365);
        }
    }
}
checkCookie();
</script>

Second species:

    <script>
//JS operation cookies method!
//Write cookies
function setCookie(c_name, value, expiredays){
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie=c_name+ "=" + escape(value) + ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
  }
//Read cookies
function getCookie(name)
{
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg))
        return (arr[2]);
    else
        return null;
}
//delete cookies
function delCookie(name)
{
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval=getCookie(name);
    if(cval!=null)
        document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}
//Use example
setCookie("username","Darren",30)
alert(getCookie("username"));
</script>

A third example

	    <html>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	    <head>
	        <script language="JavaScript" type="text/javascript">
	            
	            function addCookie(objName, objValue, objHours){//Add cookie
	                var str = objName + "=" + escape(objValue);
	                if (objHours > 0) {//No expiration time is set for 0:00, cookie s automatically disappear when browser closes
	                    var date = new Date();
	                    var ms = objHours * 3600 * 1000;
	                    date.setTime(date.getTime() + ms);
	                    str += "; expires=" + date.toGMTString();
	                }
	                document.cookie = str;
	                alert("Add to cookie Success");
	            }
	            
	            function getCookie(objName){//Gets the value of the cookie with the specified name
	                var arrStr = document.cookie.split("; ");
	                for (var i = 0; i < arrStr.length; i++) {
	                    var temp = arrStr[i].split("=");
	                    if (temp[0] == objName)
	                        return unescape(temp[1]);
	                }
	            }
	            
	            function delCookie(name){//To delete a cookie with a specified name, you can set its expiration time to a past time
	                var date = new Date();
	                date.setTime(date.getTime() - 10000);
	                document.cookie = name + "=a; expires=" + date.toGMTString();
	            }
	            
	            function allCookie(){//Read all saved cookie strings
	                var str = document.cookie;
	                if (str == "") {
	                    str = "No storage cookie";
	                }
	                alert(str);
	            }
	            
	            function $(m, n){
	                return document.forms[m].elements[n].value;
	            }
	            
	            function add_(){
	                var cookie_name = $("myform", "cookie_name");
	                var cookie_value = $("myform", "cookie_value");
	                var cookie_expireHours = $("myform", "cookie_expiresHours");
	                addCookie(cookie_name, cookie_value, cookie_expireHours);
	            }
	            
	            function get_(){
	                var cookie_name = $("myform", "cookie_name");
	                var cookie_value = getCookie(cookie_name);
	                alert(cookie_value);
	            }
	            
	            function del_(){
	                var cookie_name = $("myform", "cookie_name");
	                delCookie(cookie_name);
	                alert("Delete successful");
	            }
	        </script>
	    </head>
	    <body>
	        <form name="myform">
	            <div>
	                <label for="cookie_name">
	                    Name
	                </label>
	                <input type="text" name="cookie_name" />
	            </div>
	            <div>
	                <label for="cookie_value">
	                value
	                </lable>
	                <input type="text" name="cookie_value" />
	            </div>
	            <div>
	                <label for="cookie_expireHours">
	                How many hours expire
	                </lable>
	                <input type="text" name="cookie_expiresHours" />
	            </div>
	            <div>
	                <input type="button" value="Add this cookie" onclick="add_()"/><input type="button" value="Read all cookie" onclick="allCookie()"/><input type="button" value="Read the name cookie" onclick="get_()"/><input type="button" value="Delete the name cookie" onclick="del_()"/>
	            </div>
	        </form>
	</body>
	</html>

Be careful:
chrome browsers can't get cookie s locally. It must be on the server. If it's local, you can put it under the local www directory.
Google Chrome only supports cookie reads and writes on online websites, and is prohibited from cookie operations on local HTML. So if you write the following code in a local HTML file, the pop-up dialog will be empty.
document.cookie = "Test=cooo";
alert(document.cookie);
If this page is the content of an online website, cookie content Test=cooo and so on will normally be displayed.

Posted by Duell on Fri, 01 Feb 2019 09:45:16 -0800