답변:
function deleteAllCookies() {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
}
이 코드에는 두 가지 제한 사항이 있습니다.
HttpOnly플래그 HttpOnly가 쿠키에 대한 Javascript의 액세스를 비활성화 하므로 플래그가 설정된 쿠키는 삭제되지 않습니다 .Path값 으로 설정된 쿠키는 삭제하지 않습니다 . (이 쿠키는에 표시 document.cookie되지만 쿠키 Path와 동일한 값을 지정하지 않으면 삭제할 수 없습니다 .)trim()추가 공간이나 split('; ')( ';')이 필요합니다. 편집을 제안했습니다.
빨리 붙여 넣기를 원할 경우 ...
document.cookie.split(";").forEach(function(c) { document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); });
그리고 북마크릿의 코드 :
javascript:(function(){document.cookie.split(";").forEach(function(c) { document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); }); })();
localStorage하므로 window.localStorage.clear()도움이 될 수도 있습니다
다음은 모든 경로와 도메인의 모든 변형 (www.mydomain.com, mydomain.com 등)의 모든 쿠키를 지우는 방법입니다.
(function () {
var cookies = document.cookie.split("; ");
for (var c = 0; c < cookies.length; c++) {
var d = window.location.hostname.split(".");
while (d.length > 0) {
var cookieBase = encodeURIComponent(cookies[c].split(";")[0].split("=")[0]) + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT; domain=' + d.join('.') + ' ;path=';
var p = location.pathname.split('/');
document.cookie = cookieBase + '/';
while (p.length > 0) {
document.cookie = cookieBase + p.join('/');
p.pop();
};
d.shift();
}
}
})();
이 문제에 약간의 좌절감을 느낀 후에 나는 모든 경로에서 명명 된 쿠키를 삭제하려고 시도하는이 기능을 함께 사용했습니다. 각 쿠키마다 이것을 호출하면 이전의 모든 쿠키를 삭제하는 데 더 가깝습니다.
function eraseCookieFromAllPaths(name) {
// This function will attempt to remove a cookie from all paths.
var pathBits = location.pathname.split('/');
var pathCurrent = ' path=';
// do a simple pathless delete first.
document.cookie = name + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT;';
for (var i = 0; i < pathBits.length; i++) {
pathCurrent += ((pathCurrent.substr(-1) != '/') ? '/' : '') + pathBits[i];
document.cookie = name + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT;' + pathCurrent + ';';
}
}
항상 다른 브라우저는 다른 동작을 가지고 있지만 이것은 나를 위해 일했습니다. 즐겨.
jquery.cookie 플러그인에 액세스 할 수있는 경우 다음 방법으로 모든 쿠키를 지울 수 있습니다.
for (var it in $.cookie()) $.removeCookie(it);
내가 아는 한 도메인에 설정된 쿠키를 담요로 삭제할 수있는 방법이 없습니다. 이름을 알고 스크립트가 쿠키와 동일한 도메인에있는 경우 쿠키를 지울 수 있습니다.
값을 비우고 만료 날짜를 과거 어딘가에 설정할 수 있습니다.
var mydate = new Date();
mydate.setTime(mydate.getTime() - 1);
document.cookie = "username=; expires=" + mydate.toGMTString();
여기 에 자바 스크립트를 사용하여 쿠키를 조작 하는 것에 대한 훌륭한 기사가 있습니다 .
document.cookie="username;expires=" + new Date(0).toGMTString()- 많이하지 차이를 쿠키 초 전 또는 1970 년 1 만료되면
더 간단합니다. 더 빠릅니다.
function deleteAllCookies() {
var c = document.cookie.split("; ");
for (i in c)
document.cookie =/^[^=]+/.exec(c[i])[0]+"=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
두 번째 답변과 W3Schools의 영향을받는 답변
document.cookie.split(';').forEach(function(c) {
document.cookie = c.trim().split('=')[0] + '=;' + 'expires=Thu, 01 Jan 1970 00:00:00 UTC;';
});
작동하는 것 같습니다
편집 : 스택 오버 플로우가 서로 옆에 배치하는 Zach의 흥미로운 것과 거의 동일합니다.
편집 : 일시적으로 보이는 nvm
쿠키를 지우는 데이 방법을 공유한다고 생각했습니다. 아마도 다른 시점에서 누군가에게 도움이 될 수 있습니다.
var cookie = document.cookie.split(';');
for (var i = 0; i < cookie.length; i++) {
var chip = cookie[i],
entry = chip.split("="),
name = entry[0];
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
첫 번째로 투표 한 답변이 왜 효과가 없는지 모르겠습니다.
로 이 답변이 말했다 :
브라우저 쿠키를 삭제하는 100 % 솔루션은 없습니다.
문제는 쿠키가 키 "이름"뿐만 아니라 "도메인"및 "경로"로 고유하게 식별된다는 것입니다.
쿠키의 "도메인"및 "경로"를 모르면 쿠키를 확실하게 삭제할 수 없습니다. 이 정보는 JavaScript의 document.cookie를 통해 사용할 수 없습니다. HTTP 쿠키 헤더를 통해서도 사용할 수 없습니다!
그래서 내 생각은 전체 설정 세트로 쿠키 버전 컨트롤을 추가하고 쿠키를 가져오고 제거하는 것입니다.
var cookie_version_control = '---2018/5/11';
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name+cookie_version_control + "=" + (value || "") + expires + "; path=/";
}
function getCookie(name) {
var nameEQ = name+cookie_version_control + "=";
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,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function removeCookie(name) {
document.cookie = name+cookie_version_control+'=; Max-Age=-99999999;';
}
let expireTime = now.getTime(); now.setTime(expireTime); document.cookie =document.cookie+';expires='+now.toUTCString()+';path=/'; 은 쿠키를 제거합니다.
좀 더 정교하고 OOP 지향적 인 쿠키 제어 모듈이 있습니다. deleteAll기존의 모든 쿠키를 지우는 방법 도 포함되어 있습니다 . 이 버전의 deleteAll메소드에는 path=/현재 도메인 내의 모든 쿠키가 삭제되도록 설정 되어 있습니다. 일부 범위에서만 쿠키를 삭제 해야하는 경우이 방법을 동적 path매개 변수를 추가 하여이 방법을 업그레이드해야합니다 .
메인 Cookie클래스가 있습니다 :
import {Setter} from './Setter';
export class Cookie {
/**
* @param {string} key
* @return {string|undefined}
*/
static get(key) {
key = key.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1');
const regExp = new RegExp('(?:^|; )' + key + '=([^;]*)');
const matches = document.cookie.match(regExp);
return matches
? decodeURIComponent(matches[1])
: undefined;
}
/**
* @param {string} name
*/
static delete(name) {
this.set(name, '', { expires: -1 });
}
static deleteAll() {
const cookies = document.cookie.split('; ');
for (let cookie of cookies) {
const index = cookie.indexOf('=');
const name = ~index
? cookie.substr(0, index)
: cookie;
document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/';
}
}
/**
* @param {string} name
* @param {string|boolean} value
* @param {{expires?:Date|string|number,path?:string,domain?:string,secure?:boolean}} opts
*/
static set(name, value, opts = {}) {
Setter.set(name, value, opts);
}
}
쿠키 세터 메소드 ( Cookie.set)는 다소 복잡하므로 다른 클래스로 분해했습니다. 이것의 코드가 있습니다 :
export class Setter {
/**
* @param {string} name
* @param {string|boolean} value
* @param {{expires?:Date|string|number,path?:string,domain?:string,secure?:boolean}} opts
*/
static set(name, value, opts = {}) {
value = Setter.prepareValue(value);
opts = Setter.prepareOpts(opts);
let updatedCookie = name + '=' + value;
for (let i in opts) {
if (!opts.hasOwnProperty(i)) continue;
updatedCookie += '; ' + i;
const value = opts[i];
if (value !== true)
updatedCookie += '=' + value;
}
document.cookie = updatedCookie;
}
/**
* @param {string} value
* @return {string}
* @private
*/
static prepareValue(value) {
return encodeURIComponent(value);
}
/**
* @param {{expires?:Date|string|number,path?:string,domain?:string,secure?:boolean}} opts
* @private
*/
static prepareOpts(opts = {}) {
opts = Object.assign({}, opts);
let {expires} = opts;
if (typeof expires == 'number' && expires) {
const date = new Date();
date.setTime(date.getTime() + expires * 1000);
expires = opts.expires = date;
}
if (expires && expires.toUTCString)
opts.expires = expires.toUTCString();
return opts;
}
}
다음 은 JavaScript에서 모든 쿠키 를 삭제 하는 간단한 코드 입니다.
function deleteAllCookies(){
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
deleteCookie(cookies[i].split("=")[0]);
}
function setCookie(name, value, expirydays) {
var d = new Date();
d.setTime(d.getTime() + (expirydays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = name + "=" + value + "; " + expires;
}
function deleteCookie(name){
setCookie(name,"",-1);
}
deleteAllCookies()모든 쿠키를 지우 려면 기능 을 실행하십시오 .
const cookieCleaner = () => {
return document.cookie.split(";").reduce(function (acc, cookie) {
const eqPos = cookie.indexOf("=");
const cleanCookie = `${cookie.substr(0, eqPos)}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;`;
return `${acc}${cleanCookie}`;
}, "");
}
참고 : 경로를 처리하지 않습니다
//Delete all cookies
function deleteAllCookies() {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + '=;' +
'expires=Thu, 01-Jan-1970 00:00:01 GMT;' +
'path=' + '/;' +
'domain=' + window.location.host + ';' +
'secure=;';
}
}
여러 스타일의 쿠키에서 여러 스타일의 브라우저에 나열된 거의 모든 방법을 테스트 한 결과 50 %까지 작동하지 않는 것으로 나타났습니다.
필요에 따라 수정 해주세요.하지만 여기에 2 센트를 넣을 것입니다. 다음 방법은 모든 것을 분류하고 기본적으로 설정 조각과 경로 문자열의 단계별 빌드를 포함하여 쿠키 값 문자열을 빌드합니다./ .
이것이 다른 사람들에게 도움이되기를 바라며, 비판이이 방법을 완성시키는 형태로 나타날 수 있기를 바랍니다. 처음에는 다른 사람들이 찾던 것처럼 간단한 1 라이너를 원했지만 JS 쿠키는 그렇게 쉽게 다루지 않는 것 중 하나입니다.
;(function() {
if (!window['deleteAllCookies'] && document['cookie']) {
window.deleteAllCookies = function(showLog) {
var arrCookies = document.cookie.split(';'),
arrPaths = location.pathname.replace(/^\//, '').split('/'), // remove leading '/' and split any existing paths
arrTemplate = [ 'expires=Thu, 01-Jan-1970 00:00:01 GMT', 'path={path}', 'domain=' + window.location.host, 'secure=' ]; // array of cookie settings in order tested and found most useful in establishing a "delete"
for (var i in arrCookies) {
var strCookie = arrCookies[i];
if (typeof strCookie == 'string' && strCookie.indexOf('=') >= 0) {
var strName = strCookie.split('=')[0]; // the cookie name
for (var j=1;j<=arrTemplate.length;j++) {
if (document.cookie.indexOf(strName) < 0) break; // if this is true, then the cookie no longer exist
else {
var strValue = strName + '=; ' + arrTemplate.slice(0, j).join('; ') + ';'; // made using the temp array of settings, putting it together piece by piece as loop rolls on
if (j == 1) document.cookie = strValue;
else {
for (var k=0;k<=arrPaths.length;k++) {
if (document.cookie.indexOf(strName) < 0) break; // if this is true, then the cookie no longer exist
else {
var strPath = arrPaths.slice(0, k).join('/') + '/'; // builds path line
strValue = strValue.replace('{path}', strPath);
document.cookie = strValue;
}
}
}
}
}
}
}
showLog && window['console'] && console.info && console.info("\n\tCookies Have Been Deleted!\n\tdocument.cookie = \"" + document.cookie + "\"\n");
return document.cookie;
}
}
})();
jquery :
var cookies = $.cookie();
for(var cookie in cookies) {
$.removeCookie(cookie);
}
바닐라 JS
function clearListCookies()
{
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
{
var spcook = cookies[i].split("=");
deleteCookie(spcook[0]);
}
function deleteCookie(cookiename)
{
var d = new Date();
d.setDate(d.getDate() - 1);
var expires = ";expires="+d;
var name=cookiename;
//alert(name);
var value="";
document.cookie = name + "=" + value + expires + "; path=/acc/html";
}
window.location = ""; // TO REFRESH THE PAGE
}
IE와 Edge에서 문제를 발견했습니다. 웹킷 브라우저 (Chrome, Safari)가 더 관대 해 보입니다. 쿠키를 설정할 때는 항상 "경로"를 무언가로 설정하십시오. 기본값은 쿠키를 설정하는 페이지이기 때문입니다. 따라서 "경로"를 지정하지 않고 다른 페이지에서 만료하려고하면 경로가 일치하지 않고 만료되지 않습니다. 그만큼document.cookie당신이 쿠키 값을보고 설정 위치를 도출 할 수 있도록 값은 쿠키의 경로 또는 만료를 표시하지 않습니다.
다른 페이지에서 쿠키를 만료해야하는 경우 설정 페이지의 경로를 쿠키 값에 저장하여 나중에 가져 오거나 항상 "; path=/;"쿠키 값에 추가 할 수 있습니다 . 그러면 모든 페이지에서 만료됩니다.
name = ""대신 이름없는 값을 지우십시오.