Blocking scripts and connections
Hold back tags, pixels, iframes, and network connections until the visitor's consent allows them.
Last updated:
CookieBeam blocks non-consented resources in two complementary ways: automatic blocking driven by your scan inventory, and manual script gating for tags you mark up yourself.
Automatic blocking
The published banner includes a small interceptor that runs before your tags. It watches for script, iframe, and image insertion and neutralizes anything your configuration says needs consent:
- Scripts are rewritten in place; the
srcmoves to adata-cookieblock-srcattribute and the type becomestext/plain, so the browser downloads and executes nothing. - Iframes and images have their
srccleared, and blocked iframes can render a consent placeholder ("shield") the visitor can click to allow that embed. - Network connections:
fetch,XMLHttpRequest,navigator.sendBeacon, and WebSocket are wrapped and checked against your connection rules, so a script that did load can't quietly phone home to a denied endpoint.
What gets blocked comes from the cookie scanner's inventory (detected scripts and connections with their categories) plus any blocking rules you add yourself, compiled into the published bundle. CookieBeam's own domains are never blocked.
When the visitor consents, blocked resources for the newly allowed categories are revived: a fresh script element is cloned from the placeholder and executed, and gated connections start passing. External scripts are re-inserted with forced in-order execution, so dependency chains (a library and the tag that uses it) load in the right sequence.
Iframe consent placeholders (shields)
When the interceptor blocks an iframe, it replaces the visible area with a consent placeholder: internally called a "shield." The shield tells the visitor what was blocked and offers a one-click way to allow it.
The shield renders inside a shadow DOM attached to the blocked iframe's parent. Its styles are injected inline within the shadow root, so they don't clash with your page CSS. The trade-off is that a Content Security Policy needs 'unsafe-inline' in style-src for the shield to render correctly; see Content Security Policy for the full CSP setup.
The shield displays:
- A short explanation that the embed requires consent (customizable in the banner translations).
- The name of the category the embed belongs to.
- A button the visitor can click to allow that specific category, which writes a consent update and revives the iframe.
The shield respects the blocked iframe's dimensions. If the iframe has explicit width and height attributes or CSS sizing, the shield fills the same area. Background color and text color follow the banner's theme tokens, so it looks consistent with the rest of the consent UI.
Shields apply only to iframes, not to blocked images or scripts. A blocked image is simply not loaded; a blocked script produces no visible output. If you need a visual indicator for blocked images, wrap the <img> in a container and style the container's empty state with CSS.
Manual script gating
For tags you control in your own markup, gate them declaratively, no JavaScript required:
<script type="text/plain" data-category="marketing" data-src="https://example.com/pixel.js"></script>
The type="text/plain" keeps the browser from executing the tag; data-category binds it to one of your consent categories. When the visitor accepts that category, the runtime clones and replaces the element (mutating type in place would not execute it) and the tag runs. Inline scripts work the same way without the data-src attribute.
The attribute names above are the defaults; self-hosted configurations can remap them via the script-gating configuration.
Inline script blocking
Inline scripts (scripts with their code in the HTML body rather than loaded by URL) can be gated the same way. Set type="text/plain" and data-category, and put the script body inline:
<script type="text/plain" data-category="analytics">
(function() {
// your inline tracking snippet
})();
</script>
When the visitor accepts the category, the runtime creates a fresh <script> element with the correct type, copies the text content into it, and inserts it, triggering execution.
Framework-generated inline scripts (Next.js RSC and hydration payloads, JSON-LD structured data, Nuxt/Vue/Gatsby SSR data) are filtered out by the scanner and not considered for blocking, since they're application logic, not tracking scripts.
Script gating attributes
| Attribute | Default name | Configurable via | Purpose |
|---|---|---|---|
| Category | data-category | scriptGating.dataAttributeName | Which consent category gates this script |
| Source URL | data-src | scriptGating.srcAttributeName | Real URL for external scripts (replaces src on consent) |
| Placeholder type | type="text/plain" | scriptGating.placeholderTypeValue | Prevents the browser from executing the tag |
| Run on disable | data-cookiebeam-run-on-disable | - | Fires the script when the category is denied |
Self-hosted configurations that use different attribute names should set scriptGating in the RuntimeConfig:
scriptGating: {
dataAttributeName: 'data-consent',
srcAttributeName: 'data-consent-src',
placeholderTypeValue: 'text/plain'
}
The runtime reads these names at startup and uses them for all gating operations.
Run-on-disable scripts
Some vendors expect an explicit "the user said no" beacon rather than silence. Add data-cookiebeam-run-on-disable to a gated script and it fires when the category is denied in any valid consent record: not only after an explicit rejection:
<script type="text/plain" data-category="analytics" data-cookiebeam-run-on-disable="true" data-src="https://example.com/opt-out-beacon.js"></script>
The exact firing rules, from the shipped runtime:
- A valid consent record must exist. The runtime checks that the current record is valid and that the category is not accepted in it; it does not distinguish an explicit "no" from a machine-written default. In opt-out or notice mode, the default record written at page load is already valid, so a run-on-disable script for any category outside the default set fires on that first load, before the visitor has touched the banner. Published bundles do not write an opt-in default at page load. In opt-in mode, a visitor with no existing valid record must first produce one before the script can fire.
- Once per page load, not per browser session. The fired-once registry lives in the page's runtime memory. A toggle off → on → off in the same page view fires the script only once, but a navigation or reload builds a fresh registry and the script can fire again for a still-denied category.
If you wire an external opt-out beacon to this attribute, expect it to represent "this category is currently denied for this visitor", including visitors who never interacted, rather than "this visitor just said no".
Cookie auto-clearing on revocation
When autoClearCookies is enabled (it's on by default in the RuntimeConfig), the runtime clears cookies, localStorage keys, and sessionStorage keys listed in a category's autoClear configuration whenever that category is not in the accepted set. This runs on every consent write, including the first-load default: in opt-in mode the default write accepts only necessary categories, so auto-clear fires for all optional categories on the first page load.
Each category can declare which storage to clear:
categories: {
analytics: {
enabled: true,
readOnly: false,
autoClear: {
cookies: [
{ name: '_ga', domain: '.example.com' },
{ name: '_gid' },
{ name: /^_ga_/ } // regex matches multiple cookies
],
localStorage: ['_ga_session'],
sessionStorage: ['analytics_buffer'],
reloadPage: false
}
}
}
Cookies can be matched by exact name or by regular expression. Including a domain and path narrows the match to that specific cookie; without them, the runtime tries common domain/path combinations.
localStorage and sessionStorage entries are matched by exact key name.
reloadPage: when true, the page reloads after auto-clearing finishes for that category. Use this for vendors that cache state in memory and don't pick up cookie removal until a fresh page load. Default is false.
Auto-clearing also works at service granularity. If a category has services, each ServiceConfig can declare its own cookies list. When the visitor revokes consent for a specific service (but keeps the parent category), only that service's cookies are cleared.
The clearing runs synchronously when the visitor changes their preferences. By the time the preferences modal closes, the cookies are already gone.
Blocking and tag managers
Tags injected dynamically by Google Tag Manager, Adobe Launch, Tealium, or any other tag manager are caught by the automatic blocking interceptor. The interceptor watches the DOM for new <script> and <iframe> insertions and checks each one against the published blocking rules. No markup changes are needed for tags that a tag manager injects at runtime.
For Google Tag Manager specifically, CookieBeam provides a tighter integration:
- Consent Mode: CookieBeam fires
gtag('consent', 'default', ...)andgtag('consent', 'update', ...)calls that GTM reads natively. Tags configured with Consent Mode built-in checks respect the consent state without extra triggers. See Consent Mode v2. - dataLayer events: CookieBeam pushes consent events to the GTM
dataLayer, includingcookie_consent_updateand category-specific events (cookie_consent_marketing,cookie_consent_statistics,cookie_consent_preferences), so your custom triggers can react to consent changes. - The GTM Consent Mode template: the CookieBeam template reads the consent cookie at Consent Initialization for the fastest possible consent restore, before CookieBeam's runtime has loaded.
If you use GTM with Consent Mode, most tags don't need manual blocking rules at all; they adjust their own behavior based on the consent signals.
Connection blocking in detail
Network connection blocking works differently from script and iframe blocking. Instead of preventing an element from loading, the interceptor wraps the browser's network APIs before your code runs:
fetch(): calls are intercepted at the function level. If the URL matches a blocked connection rule, the call returns a syntheticResponse(status 204, empty body) instead of reaching the network.XMLHttpRequest.open(): theopenmethod is wrapped. A blocked request receives a synthetic error rather than completing.navigator.sendBeacon(): beacons are intercepted the same way. A blocked beacon returnstrue(so the caller believes it was sent). This catches analytics and pixel-fire beacons that many vendors use for lightweight tracking.- WebSocket: new WebSocket connections to blocked endpoints are prevented.
Connection rules come from the scanner's connection inventory and any manual rules you add. Each rule maps a URL pattern (domain, path, or regex) to a consent category. Blocked calls do not queue for later consent; they are denied immediately with a synthetic response. If the visitor later grants the category, new calls to the same endpoint go through on subsequent code paths, but the original blocked call is not replayed.
Connection blocking complements script blocking. A script that loaded (because it was allowed, or because it runs before the interceptor) can still be prevented from sending data to a non-consented endpoint. This is important for scripts that serve multiple functions; a library that handles both necessary functionality and analytics reporting can load immediately while its analytics calls are held.
Drift detection extends connection blocking to the live site. The CDN script wraps the same APIs and watches for connections to endpoints that weren't in the last scan. When it finds one, it files a drift report. After 5 reports from different visitors, the endpoint is auto-promoted into the inventory for review. See What the scanner finds.
How scripts are revived after consent
When the visitor grants a category, the runtime revives all blocked resources for that category in a specific order:
-
Scripts are cloned, not mutated. Changing
typeon an existing<script>element doesn't re-execute it. The runtime creates a new<script>element, copies the original's attributes (restoring the realsrcfromdata-cookieblock-srcordata-src), and inserts it in the same position. The placeholder element is removed. -
Execution order is preserved. External scripts in the same category are re-inserted in their original document order, with forced synchronous loading. If script B depends on script A (a common pattern: a vendor library and the tag that uses it), A runs first. This prevents race conditions where a tag tries to use a library that hasn't loaded yet.
-
Iframes are restored. Blocked iframes have their
srcattribute restored from the stored value. The shield placeholder is removed, and the iframe loads normally. -
Connections pass through. Held
fetch()andXMLHttpRequestcalls resume. Calls that were blocked before consent now go through to the network. -
Run-on-disable scripts don't fire. A script with
data-cookiebeam-run-on-disableonly fires when the category is denied. When the category is accepted, the run-on-disable script stays inert.
The revival is synchronous within the page: by the time the consent update event fires, all resources for the newly granted category are either loaded or loading. Your code can listen for cookiebeam:consentUpdate or use CookieBeam.acceptedCategory('marketing') to confirm before taking action.
Choosing between automatic and manual
Use automatic blocking for third-party tags the scanner finds and classifies; it needs no markup changes for tags added by JavaScript (a tag manager, a plugin, or another script). A <script src> hardcoded in your page HTML is different: the browser starts fetching it while parsing the HTML, before any JavaScript can intercept it, so change it to <script type="text/plain" data-category="..." data-src="..."> as shown under manual gating. Use manual gating when you want deterministic, reviewable control over a specific tag, or when you inline first-party scripts that set cookies. The two compose: a manually gated script is never double-activated by the automatic engine.
| Scenario | Approach |
|---|---|
| Third-party tag injected by a tag manager | Automatic blocking |
Third-party tag hardcoded in your HTML <head> | Manual gating (type="text/plain" + data-category) |
| Inline first-party script that sets a cookie | Manual gating |
| Network connection to a tracking endpoint | Automatic blocking (connection rules) |
| Iframe embed (YouTube, map, social) | Automatic blocking + shield placeholder |
| Vendor opt-out beacon | Manual gating with data-cookiebeam-run-on-disable |
Blocking and single-page applications
In a single-page application (SPA), the page doesn't fully reload on navigation. The blocking interceptor initializes once when the runtime loads and stays active for the page's lifetime. It intercepts script and iframe insertions dynamically, so tags that a SPA-based router injects on a route change are blocked the same way as tags on the initial load.
One thing to watch: if your SPA loads the CookieBeam script lazily (after the initial render), tags that fire before the script loads won't be intercepted. Load the CookieBeam script synchronously in <head>, before your application bundle, so the interceptor is in place before any tags run. See Install the script tag.
Cookie auto-clearing on consent revocation works normally in SPAs: the runtime clears cookies immediately when the visitor changes their preferences, without waiting for a navigation.
Blocking behavior by consent mode
The consent mode affects what is blocked and when:
Opt-in mode: every non-readOnly category starts blocked. No scripts, iframes, or connections in optional categories fire until the visitor explicitly accepts. This is the strictest mode, required by the ePrivacy Directive and similar opt-in frameworks that mandate prior consent for non-essential storage.
Opt-out mode: optional categories with enabled: true start unblocked. Scripts in those categories fire on page load, before the visitor interacts. If the visitor later opts out, the blocked categories are enforced on the next page load. Combined with autoClearCookies, revoking a category clears its cookies immediately.
Notice mode: all categories are active. The banner informs the visitor but doesn't gate anything. Blocking rules still exist in the configuration but have no effect; everything is allowed.
When you use regional rules, the blocking behavior can differ per visitor. A visitor in Germany gets opt-in blocking; a visitor in California gets opt-out; a visitor in a region with no rule gets the fallback behavior. The same banner, the same set of blocking rules, but different enforcement at runtime.
Verify blocking end to end
- Publish the banner after any blocking rule change; the interceptor runs from the published bundle, not the saved draft.
- Open your site in a private browser window (no stored consent, no extensions that might interfere).
- Open the browser's Network panel. Filter by the domain of a tag you expect to be blocked.
- Confirm the tag does not fire before you interact with the banner.
- Accept the category that the tag belongs to.
- Confirm the tag does fire after consent.
- Revoke the category in the preferences panel. If
autoClearCookiesis on, confirm the vendor's cookies are removed (check the Application → Cookies panel). - Reload the page and confirm the tag is blocked again; the revoked category should not fire on the next load.
For connection blocking, check the Network panel for fetch and XMLHttpRequest requests to the blocked endpoint. The interceptor prevents them from completing; you'll see them absent rather than cancelled.
If a tag fires before consent, check these common causes:
- The script tag is in your HTML with a normal
type: it runs before the interceptor loads. Convert it to manual gating. - The tag is not in your scan inventory; run a new scan and classify the result.
- The banner was not published after the rule change.
- A cached version of the banner is being served; wait for the CDN cache to expire or trigger a purge.
- The script loads from a different domain than what the inventory rule covers. Check the exact domain in the Network panel against the blocking rule's domain pattern.
- A connection fires to a different endpoint than the one in the inventory. Analytics vendors often rotate their collection domains.
If auto-clearing doesn't work:
- Check that
autoClearCookiesistruein the banner configuration (it's on by default). - Check that the category's
autoClear.cookieslist matches the cookie names exactly. Use regex entries for cookies with dynamic suffixes (like_ga_*). - A cookie set with a
domainthat doesn't match thedomainin the auto-clear entry won't be deleted. Check both the cookie's domain and the entry's domain in the developer tools. - Some cookies are
HttpOnly: JavaScript can't delete them. The runtime can only clear cookies that JavaScript has access to. - Clearing
localStorageandsessionStorageentries requires the exact key name, no regex matching is available for storage keys.
What blocking cannot reach
CookieBeam's script and connection blocking runs inside the visitor's browser. Some data-sharing techniques happen outside that scope:
- Cross-origin iframes with server-side tracking. An iframe loaded from a third-party origin can set cookies and send data from its own server. The iframe itself can be blocked by category, but once allowed, the server behind it is outside the page's control.
- Server-to-server syncs. When your backend shares data with a vendor's API (a server-side tag, a webhook, a data export), no client-side tool can intercept that call. Gate server-side sends on the consent decision your server recorded, not on the banner alone.
- Redirect-based cookie syncs. Some advertising networks bounce the visitor through a chain of redirects to sync identifiers across domains. Each redirect sets its own cookie before the visitor reaches the destination. This happens at the HTTP level, before JavaScript runs. Browser privacy features (ITP, ETP, bounce-tracking mitigations) reduce these, but CookieBeam cannot block a redirect the browser has already followed.
If your scan turns up a sync endpoint that CookieBeam blocks as a connection, that covers the client-side request. It does not cover the same sync happening through a redirect, an iframe's server, or a server-to-server call. Run your server-side integrations against the same consent categories the banner enforces on the client.
Related pages
- What the scanner finds; how items enter the inventory
- Categories, services, and purposes: the building blocks blocking enforces
- Consent Mode v2; how Google tags use consent signals instead of blocking
- Content Security Policy: the CSP entries CookieBeam's blocking needs