Gate GA4 on consent
Goal: keep your own GA4 setup code from running until the visitor consents to the analytics category, and run it the moment they do.
OptSens already integrates Google Consent Mode v2. The Google tag loads but stays denied until consent. This recipe is for the case where you
inject your own gtag('config', ...) and want it to wait for consent.
Tag the config inline
Mark your GA4 config script with type="text/plain" and
data-os-category="analytics". It will not execute until analytics is
consented, then runs automatically.
<!-- The Google tag loads normally; Consent Mode holds it at denied -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX"></script>
<!-- Your config waits for analytics consent -->
<script type="text/plain" data-os-category="analytics">
window.dataLayer = window.dataLayer || [];
function gtag(){ dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', 'G-XXXXXXX');
</script>
Replace G-XXXXXXX with your Measurement ID.
Alternative: react to the consent event
If your analytics setup lives in your application code, listen for the
consent_update event instead:
OptSens.on('consent_update', function (consent) {
if (consent.analytics) {
gtag('config', 'G-XXXXXXX');
}
});
The consent_update event replays for late subscribers. This still runs if consent was already given before your code loaded. See
Events.
Verify
- Open your site in a private window and reject analytics.
- In DevTools, confirm no
collectrequest goes to Google Analytics. - Open the preference center, accept analytics and save.
- The
collectrequest now fires, andOptSens.hasConsent('analytics')returnstruein the console.
Related pages
- Manual script tagging for the data attributes.
- Google Consent Mode v2 for the automatic integration.
- Programmatic script loading to load a script from code.