Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions assets/cookie-notice/frontconsent-cookie-notice.js
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
2 changes: 1 addition & 1 deletion assets/cookie-notice/frontconsent-cookie-notice.min.js

Large diffs are not rendered by default.

62 changes: 61 additions & 1 deletion includes/Frontend/CookieNotice.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -487,6 +530,8 @@ public function enqueue_assets() {
false
);

$consent_mode = self::get_consent_mode_settings();

wp_localize_script(
'frontconsent-cookie-notice',
'frcnCookieNotice',
Expand All @@ -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'],
),
)
);

Expand Down Expand Up @@ -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 || [];
Expand Down Expand Up @@ -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}
} )();
";

Expand Down
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
135 changes: 135 additions & 0 deletions tests/Unit/CookieNoticeConsentModeSettingsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
<?php
/**
* Tests for the extra Google Consent Mode settings sent with the default state.
*
* @package FrontConsent
*/

use FrontConsent\Frontend\CookieNotice;
use Yoast\WPTestUtils\WPIntegration\TestCase;

/**
* Consent Mode settings test case.
*/
class CookieNoticeConsentModeSettingsTest extends TestCase {

/**
* CookieNotice instance under test.
*
* @var CookieNotice
*/
private $cookie_notice;

/**
* Enable the banner and build the CookieNotice instance.
*
* @return void
*/
public function set_up() {
parent::set_up();
update_option( 'frontconsent_settings', array( 'enable_cookie_notice' => 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 );
}
}
100 changes: 100 additions & 0 deletions tests/js/consent-mode-defaults.test.js
Original file line number Diff line number Diff line change
@@ -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);
});
Loading