diff --git a/packages/cookie-banner/src/activation.ts b/packages/cookie-banner/src/activation.ts index 2e6184a6c..b5e7e03bb 100644 --- a/packages/cookie-banner/src/activation.ts +++ b/packages/cookie-banner/src/activation.ts @@ -383,29 +383,6 @@ export function deactivateElements( } } -export function activateElements( - consentData: Record, -): void { - const elements = document.querySelectorAll(`[${ATTR_CATEGORY}]`); - for (const el of elements) { - tryActivate(el, consentData); - } -} - -export function addPlaceholders( - consentData: Record, - categoryLabels: Record, - texts?: BannerTexts, -): void { - const elements = document.querySelectorAll(`[${ATTR_CATEGORY}]`); - for (const el of elements) { - const category = el.getAttribute(ATTR_CATEGORY); - if (!category || consentData[category]) continue; - if (!VISUAL_TAGS.has(el.tagName)) continue; - createPlaceholder(el, category, categoryLabels[category], texts); - } -} - function tryPlaceholder( el: Element, consentData: Record, @@ -423,6 +400,12 @@ export function observeAndActivate( categoryLabels: Record, texts?: BannerTexts, ): MutationObserver { + const existing = document.querySelectorAll(`[${ATTR_CATEGORY}]`); + for (const el of existing) { + tryActivate(el, consentData); + tryPlaceholder(el, consentData, categoryLabels, texts); + } + const observer = new MutationObserver((mutations) => { for (const mutation of mutations) { for (const node of mutation.addedNodes) { diff --git a/packages/cookie-banner/src/client.ts b/packages/cookie-banner/src/client.ts index ab5e9936b..37d7a0434 100644 --- a/packages/cookie-banner/src/client.ts +++ b/packages/cookie-banner/src/client.ts @@ -13,8 +13,6 @@ // PERFORMANCE OF THIS SOFTWARE. import { - activateElements, - addPlaceholders, deactivateElements, observeAndActivate, } from "./activation"; @@ -180,6 +178,8 @@ export class CookieBannerClient { if (!this.consent && this.gpcDetected) { this.gpc(); this._gpcApplied = true; + } else if (!this.consent) { + this.activate(this.buildDefaultConsentData()); } void flush(this.bannerId); @@ -294,6 +294,16 @@ export class CookieBannerClient { .catch(() => enqueue(this.bannerId, url.href, body)); } + private buildDefaultConsentData(): Record { + const cfg = this.config; + const consentData: Record = {}; + for (const cat of cfg.categories) { + consentData[cat.slug] = + cfg.consent_mode === "OPT_OUT" || cat.kind === "NECESSARY"; + } + return consentData; + } + private activate(consentData: Record): void { for (const integration of this.integrations) { integration.update(this.config.categories, consentData); @@ -308,8 +318,6 @@ export class CookieBannerClient { const texts = this.config.texts; deactivateElements(consentData, categoryCookies, categoryLabels, texts); - activateElements(consentData); - addPlaceholders(consentData, categoryLabels, texts); if (this.observer) { this.observer.disconnect(); }