How to Gate Non-Essential Scripts and Beacons Using Explicit Consent Logic
Captain Compliance provides a lightweight execution-gating helper that controls whether a script or beacon runs at all, based on the visitor’s consent. It’s for code that Google Tag Manager doesn’t control: scripts hard-coded in the page, embedded inline, or injected by vendor SDKs. Used alongside native consent settings in GTM, it closes the gap between what GTM governs and what the page itself does. The full helper code is included in this article.
When this is necessary
GTM’s consent settings and the CC - Consent Ready trigger are usually enough for tags that GTM loads. Execution gating is for everything else:
Third-party scripts hard-coded in the HTML
Inline scripts that read the URL, referrer or search terms and pass them along
Beacons or fetch calls to vendor endpoints
Code injected by an SDK rather than by a tag
Two things to be clear about:
This is about execution, not cookies. The helper doesn’t set, block, clear or nullify cookies. It decides whether the JavaScript runs. If it doesn’t run, no request is made, whether or not cookies would have been involved. That matters because many of the requests cited in privacy demand letters carry search terms or page context and don’t depend on cookies at all.
It isn’t retroactive. The helper can’t stop a request that has already been sent. A script embedded directly in the HTML runs during page load and can’t be controlled afterwards; it has to be removed from the static HTML and reintroduced through a consent-aware loader, as in Example 3.
How to apply execution gating
Add the helper code from the next section to your site and load it before any gated script, normally in the <head>. It exposes a CaptainCompliance object with these functions:
CaptainCompliance.executeIfConsent(category, callback)runs the callback only if the category is granted.CaptainCompliance.loadScriptIfConsent(category, url)loads a script only if the category is granted.CaptainCompliance.hasConsent(category)returns true if the category is granted.CaptainCompliance.getConsentStatus()returns the overall status stored with the visitor’s choice, or null if no choice is stored.CaptainCompliance.onConsentChange(callback)calls the callback when the stored choice changes. It checks once per second.
The category is one of PERFORMANCE, TARGETING or FUNCTIONALITY, matching the banner’s categories.
The helper reads the cc_consent_preference cookie. If the cookie is missing or cannot be read, or the visitor has not allowed the category, the helper treats the category as not granted and the code does not run.
The helper code
Copy this code into a script in your <head>, or save it as a file on your own site and load that file before any gated script.
/**
* Captain Compliance Cookie Consent Checker
*
* This script provides functions to check consent status from the Captain Compliance cookie.
* Use this to conditionally load scripts based on user consent without requiring GTM.
*/
// Main Captain Compliance namespace
window.CaptainCompliance = (function() {
// Cookie parser helper function
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
return null;
}
// Parse the Captain Compliance cookie
function getParsedCookie() {
const cookieValue = getCookie('cc_consent_preference');
if (!cookieValue) return null;
try {
return JSON.parse(cookieValue);
} catch(e) {
console.error('Error parsing Captain Compliance cookie:', e);
return null;
}
}
// Check if a specific cookie category has consent
function hasConsent(category) {
const parsed = getParsedCookie();
// If cookie doesn't exist or is malformed, default to false (no consent)
if (!parsed || !parsed.selectedCookies) {
return false;
}
// Check overall consent status first
if (parsed.status !== "ALLOWED") {
return false;
}
// Check specific category
switch(category.toUpperCase()) {
case 'STRICTLY_NECESSARY':
case 'STRICTLY_NECESSARY_COOKIES':
return parsed.selectedCookies.STRICTLY_NECESSARY_COOKIES === true;
case 'FUNCTIONALITY':
case 'FUNCTIONALITY_COOKIES':
return parsed.selectedCookies.FUNCTIONALITY_COOKIES === true;
case 'PERFORMANCE':
case 'PERFORMANCE_COOKIES':
return parsed.selectedCookies.PERFORMANCE_COOKIES === true;
case 'TARGETING':
case 'TARGETING_COOKIES':
return parsed.selectedCookies.TARGETING_COOKIES === true;
case 'UNCLASSIFIED':
case 'UNCLASSIFIED_COOKIES':
return parsed.selectedCookies.UNCLASSIFIED_COOKIES === true;
default:
console.warn('Unknown consent category:', category);
return false;
}
}
// Get overall consent status
function getConsentStatus() {
const parsed = getParsedCookie();
return parsed ? parsed.status : null;
}
// Execute a function only if consent is given
function executeIfConsent(category, callback) {
if (hasConsent(category)) {
callback();
} else {
console.log(`Script not executed: consent for ${category} not granted`);
}
}
// Load a script only if consent is given
function loadScriptIfConsent(category, scriptUrl, async = true, defer = false) {
if (hasConsent(category)) {
const script = document.createElement('script');
script.src = scriptUrl;
script.async = async;
script.defer = defer;
document.head.appendChild(script);
return script;
} else {
console.log(`Script not loaded: consent for ${category} not granted`);
return null;
}
}
// Set up a consent change listener
function onConsentChange(callback) {
let previousCookie = JSON.stringify(getParsedCookie());
// Check periodically for changes
setInterval(() => {
const currentCookie = JSON.stringify(getParsedCookie());
if (currentCookie !== previousCookie) {
previousCookie = currentCookie;
callback(getParsedCookie());
}
}, 1000);
}
// Public API
return {
hasConsent: hasConsent,
getConsentStatus: getConsentStatus,
executeIfConsent: executeIfConsent,
loadScriptIfConsent: loadScriptIfConsent,
onConsentChange: onConsentChange,
_getParsedCookie: getParsedCookie // exposed for debugging
};
})();The examples below target the kinds of requests that commonly appear in privacy complaints: third-party transmissions of search terms or page context, including ones that happen with cookies blocked.
Example 1: An inline script that leaks search terms
Risk: an inline script reads the page URL or its query string and exposes it to analytics, personalization or testing tools, regardless of how those tools are governed elsewhere.
What to look for, after selecting Reject and running a site search:
Inline scripts referencing
location.href,document.referrerorURLSearchParams(location.search)Third-party requests that contain the search term despite analytics being blocked
Search values inside analytics request payloads
Remediation: gate the script, and stop exposing the raw search value while you’re at it.
<script>
CaptainCompliance.executeIfConsent("PERFORMANCE", function () {
const params = new URLSearchParams(location.search);
window.pageContext = {
page: location.origin + location.pathname,
search_present: params.has("q")
};
});
</script>Success: after Reject and a site search, no third-party request includes the search term in its URL, referrer or payload.
Example 2: A hard-coded beacon that transmits search data
Risk: an inline beacon or fetch call sends the page URL or search term to a third-party endpoint. These usually don’t rely on cookies, which is why cookie blocking doesn’t catch them.
What to look for, after Reject:
Requests to third-party domains
Request URLs or payloads containing
location.hrefor query parameters such as?q=Raw search values
Remediation: gate the request so it never fires without consent, and minimize what it sends.
<script>
CaptainCompliance.executeIfConsent("TARGETING", function () {
const params = new URLSearchParams(location.search);
fetch("https://vendor.example/collect", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
page: location.origin + location.pathname,
search_present: params.has("q")
})
});
});
</script>Success: after Reject and a site search, no third-party request includes the search term in its URL, referrer or payload.
Example 3: Replace a hard-coded third-party script with a consent-aware loader
Risk: a third-party script tag in the HTML runs on load and sends URL, referrer or page content before any consent decision.
What to look for:
A vendor script tag in the page source
Third-party requests firing on page load, before or regardless of consent
Remediation: remove the script tag from the HTML and load the script through the helper.
<script>
CaptainCompliance.loadScriptIfConsent(
"TARGETING",
"https://cdn.vendor.com/sdk.js"
);
</script>Success: after Reject, the vendor script does not load and no third-party request fires before consent.
Verifying
Test with the browser’s network panel open, from an opt-in region with Reject selected and from any region with GPC on. Run a site search and check every third-party request for the search term, the full URL and the referrer. Then select Allow and confirm the gated scripts run. The testing article covers the full set of scenarios for the GTM side; use the same regions and choices here.
Related articles
How to Fire Early-Loading Tags After Consent with CC - Consent Ready
How to Clear Local & Session Storage on Tracking Opt-Out (Beyond Cookies)
How to Integrate Google Tag Manager (GTM) with Captain Compliance
How to Block Scripts Before Consent with Auto Blocking and Strict Mode
How to Manage Consent for Fonts, Embedded Forms, Videos, and Other Third-Party Content
