This article explains how to programmatically hook into the consent state of the WebToffee GDPR Cookie Consent plugin. This is useful when the automatic script blocker does not cover a specific third-party script or iframe, and you need to conditionally execute or suppress scripts based on the user’s consent choices.
When Do You Need the JS API?
The plugin automatically blocks many common third-party scripts (such as Google Analytics and Facebook Pixel) using predefined patterns. However, in some cases — such as YouTube iframes embedded via Gutenberg blocks — the automatic blocker may not fully prevent script execution.
In these scenarios, you can use the plugin’s JavaScript API to listen for consent changes and handle the blocking or loading of scripts manually.
Available JavaScript Events
1. wcc_consent_update
This event fires after a user interacts with the cookie banner — for example, after clicking Accept, Reject, or saving custom preferences. Use this event to react to consent changes in real time.
Use case: Execute or suppress a script immediately after the user makes a consent choice.
javascript
2. _wccBannerVisible
This event fires when the banner initializes or becomes visible on page load. Use this event to check previously stored consent values and conditionally execute scripts based on the user’s existing consent state — before any new interaction takes place.
Use case: On page load, check whether the user has already consented in a previous session and act accordingly.
javascript
Note: getWccConsent() is a helper function provided by the plugin that returns the currently stored consent data, including category-level consent values.
Practical Example — Handling YouTube iframes Manually
If YouTube videos embedded via Gutenberg blocks are not being blocked by the plugin’s script blocker, you can use the JS API to handle this manually. One approach is to load YouTube in nocookie mode using a theme filter, combined with the wcc_consent_update event to control when the embed renders.
Alternatively, listen for consent and replace the iframe src conditionally:
javascript
Important Notes
- GTM execution order: If Google Tag Manager (GTM) is loading before the plugin sends its default consent signal, analytics or marketing tags may fire before consent restrictions apply. Ensure the GTM script loads after the plugin’s consent initialization. If you are using the GTM4WP plugin, refer to the Configuring GTM article for guidance.
- Script blocker vs JS API: The script blocker prevents scripts from loading based on URL patterns. The JS API gives you programmatic control for cases where pattern-based blocking is insufficient.
- These events work alongside Google Consent Mode v3. For GCM-specific setup, refer to Implementing Google Consent Mode v3.