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.
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!