diff --git a/assets/cookie-notice/frontconsent-cookie-notice.js b/assets/cookie-notice/frontconsent-cookie-notice.js index 73344ce..44895e9 100644 --- a/assets/cookie-notice/frontconsent-cookie-notice.js +++ b/assets/cookie-notice/frontconsent-cookie-notice.js @@ -384,7 +384,23 @@ }; } + var consentMode = frcnCookieNotice.consentMode || {}; + var waitForUpdate = parseInt(consentMode.waitForUpdate, 10); + + // Added last, so an add-on's state above keeps it too. + if (waitForUpdate > 0) { + state.wait_for_update = waitForUpdate; + } + window.gtag('consent', 'default', state); + + if (consentMode.adsDataRedaction && '0' !== consentMode.adsDataRedaction) { + window.gtag('set', 'ads_data_redaction', true); + } + + if (consentMode.urlPassthrough && '0' !== consentMode.urlPassthrough) { + window.gtag('set', 'url_passthrough', true); + } } function requestTrackingIfNeeded() { diff --git a/assets/cookie-notice/frontconsent-cookie-notice.min.js b/assets/cookie-notice/frontconsent-cookie-notice.min.js index 8981cc1..a2ff58c 100644 --- a/assets/cookie-notice/frontconsent-cookie-notice.min.js +++ b/assets/cookie-notice/frontconsent-cookie-notice.min.js @@ -1 +1 @@ -!function(){"use strict";function e(e){var n=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));if(!n)return"";try{return decodeURIComponent(n[1])}catch(e){return""}}function n(e,n){return n.some(function(n){return"*"===n.charAt(n.length-1)?0===e.indexOf(n.slice(0,-1)):e===n})}function o(e){var o=Array.isArray(frcnCookieNotice.purgeCookies)?frcnCookieNotice.purgeCookies:[];if(!e&&"function"==typeof window.frcnCookieNoticeFilterPurgePatterns)try{var t=window.frcnCookieNoticeFilterPurgePatterns(o.slice());Array.isArray(t)&&t.every(function(e){return"string"==typeof e&&""!==e})&&(o=t)}catch(e){}if(o.length&&(function(e){["localStorage","sessionStorage"].forEach(function(o){try{var t=window[o];if(!t)return;for(var i=[],c=0;c0&&(t.wait_for_update=c);window.gtag("consent","default",t),i.adsDataRedaction&&"0"!==i.adsDataRedaction&&window.gtag("set","ads_data_redaction",!0);i.urlPassthrough&&"0"!==i.urlPassthrough&&window.gtag("set","url_passthrough",!0)}(),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",r):r();var c=!1;function a(){var o=document.getElementById("frcn-cookie-reopen");if(o){var n=e(frcnCookieNotice.cookieName);"accepted"!==n&&"rejected"!==n||(o.hidden=!1,c||(c=!0,o.addEventListener("click",function(){document.cookie=frcnCookieNotice.cookieName+"=; path="+frcnCookieNotice.cookiePath+"; max-age=0; SameSite=Lax",function(e,o){var t;try{t=new CustomEvent(e,{detail:o})}catch(n){(t=document.createEvent("CustomEvent")).initCustomEvent(e,!0,!0,o)}document.dispatchEvent(t)}("frcnCookieConsentWithdrawn",null),window.dataLayer=window.dataLayer||[],window.gtag=window.gtag||function(){window.dataLayer.push(arguments)},window.gtag("consent","update",{ad_storage:"denied",ad_user_data:"denied",ad_personalization:"denied",analytics_storage:"denied"}),t(!0),frcnCookieNotice.isPolicyPage&&frcnCookieNotice.homeUrl?window.location.href=frcnCookieNotice.homeUrl:window.location.reload()})))}}function r(){if("undefined"!=typeof frcnCookieNotice){var o="undefined"!=typeof frcnCookieNoticeA11y?frcnCookieNoticeA11y:{bannerOpened:"Cookie consent banner opened.",accepted:"Cookies accepted.",rejected:"Cookies rejected."};i(),a(),"accepted"!==e(frcnCookieNotice.cookieName)&&t();var c=document.getElementById("frcn-cookie-notice");if(c&&!function(o){var t=e(frcnCookieNotice.cookieName);return!("function"==typeof window.frcnCookieNoticeIsConsentStale&&window.frcnCookieNoticeIsConsentStale()||!o||"accepted"!==t&&"rejected"!==t||(o.style.display="none",0))}(c)){var r,d=c.querySelector('[data-frcn-cookie-action="accept"]'),s=c.querySelector('[data-frcn-cookie-action="reject"]'),f=c.classList.contains("frcn-cookie-notice--popup"),u=document.activeElement,w=document.getElementById("frcn-cookie-notice-announcer");r=f?150:20,window.setTimeout(function(){c.classList.remove("frcn-cookie-notice--init"),m(o.bannerOpened),f&&(document.body.classList.add("frcn-cookie-notice-lock-scroll"),d&&d.focus({preventScroll:!0}),document.addEventListener("keydown",k))},r),d&&d.addEventListener("click",function(e){e.preventDefault(),y("accepted")}),s&&s.addEventListener("click",function(e){e.preventDefault(),y("rejected")});var l=c.querySelector('[data-frcn-cookie-action="customize"]');l&&l.addEventListener("click",function(){var e;try{e=new CustomEvent("frcnCookieNoticeCustomize")}catch(o){(e=document.createEvent("CustomEvent")).initCustomEvent("frcnCookieNoticeCustomize",!0,!0,null)}document.dispatchEvent(e)});var p=!1}}function m(e){w&&(w.textContent=e)}function g(e){var o=Array.prototype.slice.call(c.querySelectorAll('a[href], button, input, [tabindex]:not([tabindex="-1"])'));if(o.length){var t=o[0],n=o[o.length-1];e.shiftKey&&document.activeElement===t?(e.preventDefault(),n.focus()):e.shiftKey||document.activeElement!==n||(e.preventDefault(),t.focus())}}function k(e){"Tab"===e.key?g(e):"Escape"!==e.key&&"Esc"!==e.key||(e.preventDefault(),y("rejected"))}function y(e){p||(p=!0,function(e){var o=24*parseInt(frcnCookieNotice.expirationDays,10)*60*60,t="https:"===window.location.protocol?"; Secure":"";document.cookie=frcnCookieNotice.cookieName+"="+e+"; path="+frcnCookieNotice.cookiePath+"; max-age="+o+"; SameSite=Lax"+t}(e),function(e){var o="accepted"===e?"granted":"denied";window.dataLayer=window.dataLayer||[],window.gtag=window.gtag||function(){window.dataLayer.push(arguments)},window.gtag("consent","update",{ad_storage:o,ad_user_data:o,ad_personalization:o,analytics_storage:o})}(e),m("accepted"===e?o.accepted:o.rejected),function(){c.classList.add("frcn-cookie-notice--hidden"),document.body.classList.remove("frcn-cookie-notice-lock-scroll"),document.removeEventListener("keydown",k),f&&u&&"function"==typeof u.focus&&u.focus({preventScroll:!0});window.setTimeout(function(){c.parentNode&&c.parentNode.removeChild(c)},300)}(),a(),function(e){var o;try{o=new CustomEvent("frcnCookieConsent",{detail:{consent:e}})}catch(t){(o=document.createEvent("CustomEvent")).initCustomEvent("frcnCookieConsent",!0,!0,{consent:e})}document.dispatchEvent(o)}(e),function(e){var o=new FormData;o.append("action","frcn_get_cookie_notice_log_nonce"),fetch(frcnCookieNotice.ajaxUrl,{method:"POST",credentials:"same-origin",body:o}).then(function(e){return e.json()}).then(function(o){if(o&&o.success&&o.data){var t=new FormData;return t.append("action","frcn_log_cookie_consent"),t.append("nonce",o.data.nonce),t.append("decision",e),fetch(frcnCookieNotice.ajaxUrl,{method:"POST",credentials:"same-origin",body:t})}}).catch(function(){})}(e),"accepted"===e?n():t())}}}(); \ No newline at end of file diff --git a/includes/Frontend/CookieNotice.php b/includes/Frontend/CookieNotice.php index a2c5b61..626571a 100644 --- a/includes/Frontend/CookieNotice.php +++ b/includes/Frontend/CookieNotice.php @@ -122,6 +122,49 @@ public static function get_gated_script_handles() { return is_array( $handles ) ? array_map( 'strval', $handles ) : array(); } + /** + * Extra Google Consent Mode settings sent with the default state: + * + * - wait_for_update: milliseconds Google tags wait for the visitor's + * stored or new decision before sending their first hit, so a tag that + * loads before this plugin's update still uses the right state. + * - ads_data_redaction: while ad_storage is denied, ad click identifiers + * are removed from Google Ads and Floodlight requests. + * - url_passthrough: while storage is denied, click identifiers (gclid, + * dclid…) are passed in the URL of internal links instead. Off by + * default: it changes the site's URLs. + * + * @return array{wait_for_update: int, ads_data_redaction: bool, url_passthrough: bool} + */ + public static function get_consent_mode_settings() { + /** + * Filters the milliseconds Google tags wait for a consent update. 0 disables it. + * + * @param int $milliseconds Default 500. + */ + $wait_for_update = (int) apply_filters( 'frcn_cookie_notice_consent_mode_wait_for_update', 500 ); + + /** + * Filters whether ad click identifiers are redacted while ad_storage is denied. + * + * @param bool $redact Default true. + */ + $ads_data_redaction = (bool) apply_filters( 'frcn_cookie_notice_consent_mode_ads_data_redaction', true ); + + /** + * Filters whether click identifiers are passed through internal link URLs while storage is denied. + * + * @param bool $passthrough Default false. + */ + $url_passthrough = (bool) apply_filters( 'frcn_cookie_notice_consent_mode_url_passthrough', false ); + + return array( + 'wait_for_update' => max( 0, $wait_for_update ), + 'ads_data_redaction' => $ads_data_redaction, + 'url_passthrough' => $url_passthrough, + ); + } + /** * Cookie names deleted client-side when the visitor rejects or withdraws * consent. An entry ending in '*' matches every cookie starting with that @@ -487,6 +530,8 @@ public function enqueue_assets() { false ); + $consent_mode = self::get_consent_mode_settings(); + wp_localize_script( 'frontconsent-cookie-notice', 'frcnCookieNotice', @@ -509,6 +554,13 @@ public function enqueue_assets() { 'isPolicyPage' => $this->is_policy_page(), 'homeUrl' => home_url( '/' ), 'purgeCookies' => self::get_purge_cookie_patterns(), + // Same settings the wp_head default uses, for the CSP fallback + // in setConsentModeDefault(). + 'consentMode' => array( + 'waitForUpdate' => $consent_mode['wait_for_update'], + 'adsDataRedaction' => $consent_mode['ads_data_redaction'], + 'urlPassthrough' => $consent_mode['url_passthrough'], + ), ) ); @@ -847,7 +899,11 @@ class="frcn-cookie-notice__button frcn-cookie-notice__button--accept" * @return void */ public function render_consent_mode_default() { - $cookie_name = $this->get_cookie_name(); + $cookie_name = $this->get_cookie_name(); + $consent_mode = self::get_consent_mode_settings(); + $wait_for_update = $consent_mode['wait_for_update'] > 0 ? 'state.wait_for_update = ' . (int) $consent_mode['wait_for_update'] . ';' : ''; + $ads_data_redaction = $consent_mode['ads_data_redaction'] ? "gtag( 'set', 'ads_data_redaction', true );" : ''; + $url_passthrough = $consent_mode['url_passthrough'] ? "gtag( 'set', 'url_passthrough', true );" : ''; $code = " window.dataLayer = window.dataLayer || []; @@ -904,7 +960,11 @@ function gtag(){ window.dataLayer.push( arguments ); } }; } + // Added last, so an add-on's state above keeps it too. + {$wait_for_update} gtag( 'consent', 'default', state ); + {$ads_data_redaction} + {$url_passthrough} } )(); "; diff --git a/readme.md b/readme.md index ba63609..1a42f1c 100644 --- a/readme.md +++ b/readme.md @@ -4,7 +4,7 @@ Repository for FrontConsent, a WordPress plugin providing a GDPR/ePrivacy-compli ## Functionalities -- **Cookie Notice** — configurable cookie consent banner (bar/box/popup) that gates Google Tag Manager, GA4, and supported tracking integrations (Clientify, Brevo, ChatGPT Ads) behind consent, with Google Consent Mode v2 support for compatibility with Google Site Kit and other analytics plugins. +- **Cookie Notice** — configurable cookie consent banner (bar/box/popup) that gates Google Tag Manager, GA4, and supported tracking integrations (Clientify, Brevo, ChatGPT Ads) behind consent, with Google Consent Mode v2 support for compatibility with Google Site Kit and other analytics plugins. The default state waits 500 ms for the visitor's decision (`wait_for_update`) and redacts ad click identifiers while ads storage is denied (`ads_data_redaction`); URL passthrough is off. Filters: `frcn_cookie_notice_consent_mode_wait_for_update`, `frcn_cookie_notice_consent_mode_ads_data_redaction`, `frcn_cookie_notice_consent_mode_url_passthrough`. - **Cookieless video embeds** — YouTube iframes are switched to `youtube-nocookie.com` and Vimeo iframes get `dnt=1`, so embedded videos set no cookies before consent (filter `frcn_privacy_enhanced_embeds`). - **Acceptance stats** — aggregate accepted/rejected counter on the settings page. - **Migration from FrontBlocks** — automatically imports settings and stats from FrontBlocks Site Tools' bundled Cookie Notice module, which FrontConsent replaces. diff --git a/tests/Unit/CookieNoticeConsentModeSettingsTest.php b/tests/Unit/CookieNoticeConsentModeSettingsTest.php new file mode 100644 index 0000000..2320f72 --- /dev/null +++ b/tests/Unit/CookieNoticeConsentModeSettingsTest.php @@ -0,0 +1,135 @@ + true ) ); + $this->cookie_notice = new CookieNotice(); + } + + /** + * Reset scripts, filters and options. + * + * @return void + */ + public function tear_down() { + wp_deregister_script( 'frontconsent-cookie-notice' ); + wp_deregister_script( 'frontconsent-consent-mode-default' ); + wp_scripts()->done = array_diff( wp_scripts()->done, array( 'frontconsent-consent-mode-default', 'frontconsent-cookie-notice' ) ); + wp_deregister_style( 'frontconsent-cookie-notice' ); + remove_all_filters( 'frcn_cookie_notice_consent_mode_wait_for_update' ); + remove_all_filters( 'frcn_cookie_notice_consent_mode_ads_data_redaction' ); + remove_all_filters( 'frcn_cookie_notice_consent_mode_url_passthrough' ); + remove_all_actions( 'wp_head' ); + remove_all_actions( 'wp_footer' ); + remove_all_actions( 'wp_enqueue_scripts' ); + delete_option( 'frontconsent_settings' ); + + parent::tear_down(); + } + + /** + * Print the wp_head Consent Mode default script. + * + * @return string + */ + private function render_default() { + // wp_print_scripts() prints a handle once per request: start clean. + wp_deregister_script( 'frontconsent-consent-mode-default' ); + wp_scripts()->done = array_diff( wp_scripts()->done, array( 'frontconsent-consent-mode-default' ) ); + + ob_start(); + $this->cookie_notice->render_consent_mode_default(); + return ob_get_clean(); + } + + /** + * By default the state waits 500 ms for the update and ad click + * identifiers are redacted; URL passthrough stays off. + * + * @return void + */ + public function test_default_waits_for_the_update_and_redacts_ads_data() { + $html = $this->render_default(); + + $this->assertStringContainsString( 'state.wait_for_update = 500;', $html ); + $this->assertStringContainsString( "gtag( 'set', 'ads_data_redaction', true );", $html ); + $this->assertStringNotContainsString( 'url_passthrough', $html ); + + // Set after any add-on override, right before the default is sent. + $this->assertLessThan( strpos( $html, "gtag( 'consent', 'default', state )" ), strpos( $html, 'state.wait_for_update' ) ); + $this->assertGreaterThan( strpos( $html, 'frcnCookieNoticeIsConsentStale' ), strpos( $html, 'state.wait_for_update' ) ); + } + + /** + * Each setting can be changed with its filter. + * + * @return void + */ + public function test_settings_are_filterable() { + add_filter( 'frcn_cookie_notice_consent_mode_wait_for_update', '__return_zero' ); + add_filter( 'frcn_cookie_notice_consent_mode_ads_data_redaction', '__return_false' ); + add_filter( 'frcn_cookie_notice_consent_mode_url_passthrough', '__return_true' ); + + $html = $this->render_default(); + + $this->assertStringNotContainsString( 'wait_for_update', $html ); + $this->assertStringNotContainsString( 'ads_data_redaction', $html ); + $this->assertStringContainsString( "gtag( 'set', 'url_passthrough', true );", $html ); + } + + /** + * A negative wait is treated as off. + * + * @return void + */ + public function test_negative_wait_is_ignored() { + add_filter( + 'frcn_cookie_notice_consent_mode_wait_for_update', + function () { + return -100; + } + ); + + $this->assertSame( 0, CookieNotice::get_consent_mode_settings()['wait_for_update'] ); + $this->assertStringNotContainsString( 'wait_for_update', $this->render_default() ); + } + + /** + * The same settings reach the script's CSP fallback. + * + * @return void + */ + public function test_settings_are_localized_for_the_csp_fallback() { + add_filter( 'frcn_cookie_notice_consent_mode_url_passthrough', '__return_true' ); + + $this->cookie_notice->enqueue_assets(); + $data = wp_scripts()->get_data( 'frontconsent-cookie-notice', 'data' ); + + $this->assertStringContainsString( '"consentMode":{"waitForUpdate":500,"adsDataRedaction":true,"urlPassthrough":true}', $data ); + } +} diff --git a/tests/js/consent-mode-defaults.test.js b/tests/js/consent-mode-defaults.test.js new file mode 100644 index 0000000..ba77974 --- /dev/null +++ b/tests/js/consent-mode-defaults.test.js @@ -0,0 +1,100 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const test = require('node:test'); +const vm = require('node:vm'); + +const scriptPath = path.resolve(__dirname, '../../assets/cookie-notice/frontconsent-cookie-notice.js'); +const cookieNoticeScript = fs.readFileSync(scriptPath, 'utf8'); + +/** + * Run the script at parse time (the CSP fallback, setConsentModeDefault()) + * and return every gtag() call it queued on the dataLayer. + */ +function runDefault(consentMode, windowProps) { + const dataLayerEntries = []; + const frcnCookieNotice = { + ajaxUrl: 'https://example.test/wp-admin/admin-ajax.php', + cookieName: 'frcn_cookie_consent', + cookiePath: '/', + expirationDays: 365, + isPolicyPage: '', + homeUrl: 'https://example.test/' + }; + + if (consentMode) { + frcnCookieNotice.consentMode = consentMode; + } + + vm.runInNewContext(cookieNoticeScript, { + Array, + CustomEvent: function () {}, + Date, + FormData: function () { this.append = function () {}; }, + decodeURIComponent, + document: { + readyState: 'loading', + cookie: '', + addEventListener() {}, + getElementById() { return null; } + }, + encodeURIComponent, + fetch() { return Promise.resolve({ json: () => Promise.resolve({ success: false }) }); }, + frcnCookieNotice, + window: Object.assign({ + get dataLayer() { return dataLayerEntries; }, + set dataLayer(value) { dataLayerEntries.length = 0; dataLayerEntries.push(...value); }, + location: { protocol: 'https:' }, + setTimeout(callback) { callback(); } + }, windowProps) + }); + + return dataLayerEntries.map((entry) => Array.from(entry)); +} + +const find = (calls, command, name) => calls.find((call) => call[0] === command && call[1] === name); + +test('the default state waits for the update and redacts ads data', () => { + const calls = runDefault({ waitForUpdate: 500, adsDataRedaction: true, urlPassthrough: false }); + + assert.equal(find(calls, 'consent', 'default')[2].wait_for_update, 500); + assert.deepEqual(find(calls, 'set', 'ads_data_redaction'), ['set', 'ads_data_redaction', true]); + assert.equal(find(calls, 'set', 'url_passthrough'), undefined); +}); + +test('url_passthrough is only set when enabled', () => { + const calls = runDefault({ waitForUpdate: 500, adsDataRedaction: true, urlPassthrough: true }); + + assert.deepEqual(find(calls, 'set', 'url_passthrough'), ['set', 'url_passthrough', true]); +}); + +test('wait_for_update and ads_data_redaction can be turned off', () => { + const calls = runDefault({ waitForUpdate: 0, adsDataRedaction: false, urlPassthrough: false }); + + assert.equal('wait_for_update' in find(calls, 'consent', 'default')[2], false); + assert.equal(find(calls, 'set', 'ads_data_redaction'), undefined); +}); + +test('an add-on state keeps wait_for_update', () => { + const calls = runDefault( + { waitForUpdate: 500, adsDataRedaction: true, urlPassthrough: false }, + { + frcnCookieNoticeConsentModeState() { + return { ad_storage: 'denied', ad_user_data: 'denied', ad_personalization: 'denied', analytics_storage: 'granted' }; + } + } + ); + const state = find(calls, 'consent', 'default')[2]; + + assert.equal(state.analytics_storage, 'granted'); + assert.equal(state.wait_for_update, 500); +}); + +test('without the localized settings (older cached page) the default is sent as before', () => { + const calls = runDefault(null); + const state = find(calls, 'consent', 'default')[2]; + + assert.equal(state.analytics_storage, 'denied'); + assert.equal('wait_for_update' in state, false); + assert.equal(find(calls, 'set', 'ads_data_redaction'), undefined); +});