Skip to content

Instantly share code, notes, and snippets.

@cmcnulty
Last active March 28, 2025 18:20
Show Gist options
  • Save cmcnulty/85c10f4f2ce177e08596de35213b4459 to your computer and use it in GitHub Desktop.
Save cmcnulty/85c10f4f2ce177e08596de35213b4459 to your computer and use it in GitHub Desktop.
/**
* Cookie Blocker Script
*
* This script overrides the document.cookie setter to block cookies with specific prefixes
* from being set.
*/
(function() {
// Get the original descriptor
const originalDescriptor = Object.getOwnPropertyDescriptor(Document.prototype, 'cookie');
const originalSetter = originalDescriptor.set;
// Cookies to block - add any prefixes you want to block
const blockedPrefixes = ['wp-dark-mode-'];
// Override only the setter, keep the original getter
Object.defineProperty(Document.prototype, 'cookie', {
configurable: true,
get: originalDescriptor.get, // Use the original getter directly
set: function(value) {
// Check if this cookie should be blocked
let shouldBlock = false;
// Parse the cookie being set
const cookieParts = value.split('=');
if (cookieParts.length >= 1) {
const cookieName = cookieParts[0].trim();
// Check if the cookie starts with any of our blocked prefixes
shouldBlock = blockedPrefixes.some(prefix => cookieName.startsWith(prefix));
if (shouldBlock) {
console.debug('Blocked cookie:', cookieName);
return; // Don't set the cookie
}
}
// Set the cookie using the original setter if not blocked
return originalSetter.call(this, value);
}
});
// Clean up any existing cookies on page load
function cleanExistingCookies() {
const cookies = document.cookie.split(';');
for (const cookie of cookies) {
const [cookieName] = cookie.split('=').map(item => item.trim());
// Check if this is a cookie we want to remove
const shouldRemove = blockedPrefixes.some(prefix => cookieName.startsWith(prefix));
if (shouldRemove) {
// Force expire the cookie to remove it
document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
console.debug('Removed existing cookie:', cookieName);
}
}
}
// Clean up existing cookies when the script loads
cleanExistingCookies();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment