Reputation: 1970
I have a webpage with third-party cookies and I'm trying to disable them on page load with Javascript. This is my code:
window.addEventListener("load", function()
{
var cookies = document.cookie.split(";");
console.log("cookies = " + cookies);
for (var i = 0 ; i < cookies.length; i++)
{
var cookie_name = cookies[i].split("=")[0];
document.cookie = cookie_name + "=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT; domain=localhost;";
console.log(cookie_name + " disabled");
}
});
The first time the page is accessed, no cookies are found by the script, but the third-party cookies are installed (I've found them by inspecting via EditThisCookie plugin for Chrome). If I reload the page, cookies are found by the script, but I noticed they have been installed again.
It seems like cookies are installed after the script execution, so I'm not able to catch them after installation. How can I effectively manage to disable these cookies?
Upvotes: 0
Views: 3395
Reputation: 1822
you can this.
setCookie(cookie_name, "disabled", -1);
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
reference: https://www.w3schools.com/js/js_cookies.asp
Upvotes: 1