How to delete cookies on withdrawal?

Have more questions? Submit a request

By default our script is not removing or deleting cookies when someone withdraws their consent. To be able to do this we wrote another helper script.

This currently only works for whole categories. Service based consent is not yet supported.

 

Important!

This will only work for First party cookies set by JavaScript. Cookies that are server side or Third Party cannot be manipulated like this.

<!-- Remove cookies after withdrawal -->
<script>
(function () {
window.cf_delete_cookie =
window.cf_delete_cookie ||
function (cookie) {
var name = cookie.unmasked_name || cookie.name;
var path = cookie.path || "/";
var domain = cookie.host_key || "";
console.log("cookie for removal", { name });
document.cookie = `${name}= ; expires = Thu, 01 Jan 1970 00:00:00 GMT; path= ${path}; domain=${domain};`;
if (window.localStorage.getItem(name)) {
window.localStorage.removeItem(name);
}
if (window.sessionStorage.getItem(name)) {
window.sessionStorage.removeItem(name);
}
};

function remove_cookies(consent = {}) {
if (typeof consent !== "object") {
throw new Error("Uknnown error");
}

window.CookieFirst.fetchLatestScan()
.then(function (result) {
if (!result || !Array.isArray(result.cookies)) {
return;
}

result.cookies.forEach(function (cookie) {
<!-- category accepted or cookie is http_only -->
if (consent[cookie.cat] || cookie.http_only) {
return;
}

window.cf_delete_cookie(cookie);
});
})
.catch(console.log);
}

function handle_consent_event(e) {
var consent = e.detail || { necessary: true };
if (!window.CookieFirst) {
window.addEventListener("cf_init", function () {
remove_cookies(consent);
});
return;
}

remove_cookies(consent);
}

window.addEventListener("cf_consent", handle_consent_event);
window.addEventListener("cf_consent_loaded", handle_consent_event);
})();
</script>
<!-- End of helper script to remove cookies -->

Articles in this section

Was this article helpful?
1 out of 2 found this helpful
Share