PageSourceSearch

https://puro.earth/wp-content/plugins/cookiefirst-gdpr-cookie-cons…/js/cookiefirst-plugin-public.js?ver=2.0.0

js puro.earth collected 2026-10-02 05:24:50 UTC 7,859 bytes, 234 lines download raw bytes

1(function( $ ) {
2	'use strict';
3
4
5	/**
6	 * CookieFirst WordPress Plugin - Frontend JavaScript
7	 * Handles WordPress Consent API integration and debug functionality
8	 */
9
10	// Global variables from WordPress (passed via wp_localize_script)
11	var cookieFirstConfig = window.cookieFirstConfig || {};
12	var debugMode = cookieFirstConfig.debug_mode || false;
13	var wpConsentApiActive = cookieFirstConfig.wp_consent_api_active || false;
14	var categoryMapping = cookieFirstConfig.category_mapping || {};
15
16	/**
17	 * Debug logging function
18	 */
19	function debugLog(message, data) {
20		if (debugMode) {
21			if (data !== undefined) {
22				console.log('[CookieFirst] ' + message, data);
23			} else {
24				console.log('[CookieFirst] ' + message);
25			}
26		}
27	}
28
29	/**
30	 * Delete WordPress consent cookies by setting their expiry to Unix epoch
31	 */
32	function deleteWordPressConsentCookies() {
33		debugLog('Deleting WordPress consent cookies...');
34		
35		var cookies = document.cookie.split("; ");
36		var deletedCookies = [];
37		
38		for (var i = 0; i < cookies.length; i++) {
39			var cookie = cookies[i];
40			if (cookie.startsWith("wp_consent_")) {
41				var cookieName = cookie.split("=")[0];
42				// Set cookie to expire on January 1, 1970 (Unix epoch)
43				document.cookie = cookieName + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
44				document.cookie = cookieName + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=" + window.location.hostname + ";";
45				deletedCookies.push(cookieName);
46				debugLog('Deleted WordPress consent cookie: ' + cookieName);
47			}
48		}
49		
50		if (deletedCookies.length > 0) {
51			debugLog('Total WordPress consent cookies deleted: ' + deletedCookies.length, deletedCookies);
52		} else {
53			debugLog('No WordPress consent cookies found to delete');
54		}
55	}
56
57	/**
58	 * Initialize debug information
59	 */
60	function initializeDebugInfo() {
61		if (!debugMode) return;
62
63		debugLog('Debug mode enabled');
64		debugLog('Plugin version: ' + (cookieFirstConfig.version || 'unknown'));
65		debugLog('API key: ' + (cookieFirstConfig.api_key || 'not set'));
66		debugLog('Consent type: ' + (cookieFirstConfig.consent_type || 'opt-in'));
67		debugLog('Script loading: ' + (cookieFirstConfig.script_loading || 'do-nothing'));
68		debugLog('WP Consent API active: ' + wpConsentApiActive);
69		debugLog('Category mappings:', categoryMapping);
70
71		// Check for existing CookieFirst consent cookie immediately
72		var initialCookie = document.cookie.split("; ").find(row => row.startsWith("cookiefirst-consent="));
73		if (initialCookie) {
74			try {
75				var initialData = JSON.parse(decodeURIComponent(initialCookie.split("=")[1]));
76				debugLog('Initial consent cookie found:', initialData);
77			} catch (e) {
78				debugLog('Initial consent cookie found but could not parse:', initialCookie);
79			}
80		} else {
81			debugLog('No initial consent cookie found');
82		}
83
84		// Check if wp_set_consent is available
85		debugLog('wp_set_consent available: ' + (typeof wp_set_consent === "function"));
86	}
87
88	/**
89	 * Update WordPress consent based on CookieFirst consent data
90	 */
91	function updateWPConsent(source) {
92		debugLog('updateWPConsent called from: ' + (source || 'initial load'));
93
94		// Check if wp_set_consent is available
95		if (typeof wp_set_consent !== "function") {
96			debugLog('wp_set_consent not available');
97			return;
98		}
99
100		// Only proceed if WP Consent API is active
101		if (!wpConsentApiActive) {
102			debugLog('WP Consent API not enabled - skipping consent management');
103			return;
104		}
105
106		var cookie = document.cookie.split("; ").find(row => row.startsWith("cookiefirst-consent="));
107		if (!cookie) {
108			debugLog('No consent cookie found - deleting WordPress consent cookies');
109			// Remove any existing WordPress consent cookies when CookieFirst consent is missing
110			deleteWordPressConsentCookies();
111			return;
112		}
113
114		try {
115			var cookieValue = decodeURIComponent(cookie.split("=")[1]);
116			var consentData = JSON.parse(cookieValue);
117			debugLog('Raw consent data:', consentData);
118			debugLog('Category mapping:', categoryMapping);
119
120			// Update WordPress consent based on CookieFirst categories
121			for (var cfCategory in categoryMapping) {
122				var wpCategories = categoryMapping[cfCategory];
123				var cfConsent = consentData[cfCategory];
124
125				debugLog('Processing CF category: ' + cfCategory + ', consent: ' + cfConsent + ', mapped to WP categories:', wpCategories);
126
127				// Set consent for each mapped WordPress category
128				if (Array.isArray(wpCategories)) {
129					for (var i = 0; i < wpCategories.length; i++) {
130						var wpCategory = wpCategories[i];
131						var consentValue = cfConsent ? "allow" : "deny";
132
133						wp_set_consent(wpCategory, consentValue);
134						debugLog('Set ' + wpCategory + ' to ' + consentValue + ' based on ' + cfCategory + ' (' + (source || 'initial load') + ')');
135					}
136				}
137			}
138		} catch (e) {
139			console.error('[CookieFirst] Error parsing consent cookie:', e);
140		}
141	}
142
143	/**
144	 * Handle CookieFirst consent events
145	 */
146	function handleConsentEvent(event) {
147		debugLog('Event received: ' + event.type, event);
148		// Add a delay to ensure the cookie is updated
149		setTimeout(function() {
150			updateWPConsent(event.type);
151		}, 200);
152	}
153
154	/**
155	 * Reset all consent (for testing/admin purposes)
156	 * This function is exposed globally for manual testing
157	 */
158	function resetAllConsent() {
159		debugLog('Resetting all consent cookies...');
160		
161		// Delete CookieFirst consent cookie
162		document.cookie = "cookiefirst-consent=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
163		document.cookie = "cookiefirst-consent=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=" + window.location.hostname + ";";
164		
165		// Delete CookieFirst ID cookie/localStorage
166		document.cookie = "cookiefirst-id=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
167		document.cookie = "cookiefirst-id=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=" + window.location.hostname + ";";
168		
169		if (typeof localStorage !== 'undefined') {
170			localStorage.removeItem('cookiefirst-consent');
171			localStorage.removeItem('cookiefirst-id');
172		}
173		
174		// Delete WordPress consent cookies
175		deleteWordPressConsentCookies();
176		
177		debugLog('All consent cookies have been reset');
178		
179		// Reload the page to ensure clean state
180		if (debugMode) {
181			setTimeout(function() {
182				window.location.reload();
183			}, 1000);
184		}
185	}
186
187	/**
188	 * Initialize the plugin when DOM is ready
189	 */
190	$(function() {
191		debugLog('CookieFirst WordPress plugin initializing...');
192
193		// Initialize debug information
194		initializeDebugInfo();
195
196		// Initial check on page load
197		setTimeout(updateWPConsent, 100);
198
199		// Listen for both standard and custom CookieFirst events
200		window.addEventListener("cf_consent", handleConsentEvent);
201		window.addEventListener("cf_consent_loaded", handleConsentEvent);
202
203		// Also listen for document events (some CookieFirst versions use these)
204		document.addEventListener("cf_consent", handleConsentEvent);
205		document.addEventListener("cf_consent_loaded", handleConsentEvent);
206
207		// Expose reset function globally for testing/admin use
208		window.cookieFirstResetConsent = resetAllConsent;
209
210		// Fallback: periodically check for consent changes (only in debug mode)
211		if (debugMode) {
212			var lastConsentState = null;
213			setInterval(function() {
214				var cookie = document.cookie.split("; ").find(row => row.startsWith("cookiefirst-consent="));
215				if (cookie) {
216					var currentState = cookie.split("=")[1];
217					if (currentState !== lastConsentState) {
218						debugLog('Consent cookie changed, updating WP consent');
219						lastConsentState = currentState;
220						updateWPConsent("periodic check");
221					}
222				} else if (lastConsentState !== null) {
223					// Consent cookie was removed
224					debugLog('Consent cookie was removed, cleaning up');
225					lastConsentState = null;
226					updateWPConsent("cookie removed");
227				}
228			}, 1000);
229		}
230
231		debugLog('CookieFirst WordPress plugin initialized');
232	});
233
234})( jQuery );

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.