Home  >  Article  >  Web Front-end  >  How to delete cookies in javascript

How to delete cookies in javascript

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-04-12 16:30:565089browse

If you want to delete cookies in javascript, you first need to find the value corresponding to the name of the cookie and set it to expire; then set the value of the expire attribute to the expiration date (that is, any past date). Browse The server will automatically delete cookie files.

How to delete cookies in javascript

The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, Dell G3 computer.

I always thought that by setting the document.cookie object of javascript, I can simply set and delete the cookie value on the browser side. Many articles on the Internet also teach this, but recently I found that it is easy to set the document.cookie of javascript. The value of does not completely delete or change the cookie.

To use JavaScript to clear cookies, you must first find the value corresponding to the Name of the cookie, and then set it to expire:
The following methods are used to find the cookie:

function getCookie2(name){
    var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));  
    if(arr != null) 
        return unescape(arr[2]); 
        return null;
}

After finding it, set it to expire. Remember to set domain and path. Only if these two parameters are exactly the same as the parameters you want to delete can you delete it.

function resetNfluent(){
		alert("before=>"+document.cookie);
		var exp  = new Date();
		exp.setTime(exp.getTime() - 1);
		var cval=getCookie2('name');
		var lanObj=document.getElementById('lanOption');
		var lanSel=lanObj.value;
		alert(lanSel);
		if(lanSel=='en'){
			alert('let\'s reset nFluent');
			alert('cval=>'+cval);
			if(cval!=null){
				document.cookie="name="+cval+";
				domain=.example.com;
				expires="+exp.toGMTString()+";
				path=/";
			}else{
				document.cookie="name=;
				domain=.example.com;
				expires="+exp.toGMTString()+";
				path=/";
				}
		}else{
			alert('Don\'t need reset nFluent');
			}
		alert("after=>"+document.cookie);
    }

Recommended learning: javascript video tutorial

The above is the detailed content of How to delete cookies in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn