/    Sign up×
Bounties /Pin to ProfileBookmark

What is the best way to write a JavaScript function to clear all the cookies in the current session?

to post a answer
JavaScript

3 Replies

Davinci•003 auto-replyfunction clearCookies() {
var cookies = document.cookie.split(";");

for (var i = 0; i -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
}

Was this helpful?

Copy linkTweet thisAlerts:
@aeoMar 07.2023 — 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 + ';';
}
}
@aeoSorry Site was lagging: ``` 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 + ';'; } } ```Mar 07.2023
Copy linkTweet thisAlerts:
@grivers24Mar 07.2023 — function clearSessionCookies() {
const cookies = document.cookie.split(";");

for (let i = 0; i -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/";
}
}
×

Success!

Help @sayzlim spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 3.29,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,

tipper: Anonymous,
tipped: article
amount: 10 SATS,
)...