You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CMP(Consent Mode v2)沙箱JS无法写入dataLayer的技术咨询

问题

使用CMP提供商代码搭建GTM自定义模板,consent设置功能正常,但修改后希望在consent更新时发送自定义事件触发特定标签,却持续收到dataLayer未定义或window未定义错误,沙箱JavaScript无法与dataLayer交互。移除window和dataLayer引用后脚本可正常更新consent,但需要在updateConsentState环节发送自定义事件触发其他标签,CMP提供商认为是Google的问题拒绝协助。

原因分析

GTM自定义模板的沙箱JavaScript运行在隔离环境中,不允许直接访问全局window对象或dataLayer,这是Google为模板安全性和兼容性设置的限制,所有对全局环境的操作必须通过GTM提供的官方API完成,直接引用window.dataLayer会因沙箱隔离导致未定义错误。

解决方案

要在沙箱中向dataLayer推送事件,需使用GTM模板提供的官方方法,以下是两种可行方案:

方案1:使用data.pushEvent方法(推荐)

GTM自定义模板的沙箱环境中,data对象内置了pushEvent方法,可直接向dataLayer推送事件,无需访问全局window。修改onAccept回调中的事件推送逻辑:

onAccept : function(){
    updateConsentState({
        'analytics_storage': 'granted',
    });
    // 使用沙箱内置方法推送事件
    data.pushEvent({
        'event': 'analytics_granted',
        'category': 'Analytics',
        'action': 'Granted'
    });
},

方案2:通过注入的外部脚本操作dataLayer

如果方案1无法满足需求,可将事件推送逻辑放在injectScript加载的外部脚本中,或通过injectScript注入一段操作dataLayer的代码——外部脚本运行在主页面环境,可直接访问全局window和dataLayer:

const onSuccess = () => {
    const CookieControl = copyFromWindow('CookieControl');
    log(config);
    // 重写config中的回调,注入事件推送逻辑
    config.optionalCookies.forEach(group => {
        const originalAccept = group.onAccept;
        group.onAccept = function() {
            originalAccept.call(this);
            // 注入临时脚本推送事件
            injectScript(`
                window.dataLayer = window.dataLayer || [];
                window.dataLayer.push({
                    'event': '${group.name.toLowerCase()}_granted',
                    'category': '${group.name}',
                    'action': 'Granted'
                });
            `, ()=>{}, ()=>{});
        };
    });
    CookieControl.load(config);
    data.gtmOnSuccess();
};
修改后的完整代码示例
const log = require('logToConsole');
const setDefaultConsentState = require('setDefaultConsentState');
const updateConsentState = require('updateConsentState');
const injectScript = require('injectScript');
const copyFromWindow = require('copyFromWindow');
log('data =', data);

// set default consent
setDefaultConsentState({
    'ad_storage': 'denied',
    'analytics_storage': 'denied',
    'ad_user_data': 'denied',
    'ad_personalization':'denied',
    'functionality_storage': data.functional,
    'personalization_storage': data.functional,
    'security_storage': 'granted'
});

// start of config
var config = {
    apiKey: data.apiKey,
    logConsent: true,
    product: data.product,
    optionalCookies: [
        {
            name : 'Analytics',
            label: "<strong>Analytics cookies</strong>",
            description: "<p>Analytics cookies help us to improve our website by collecting data about how you use it.</p>",
            cookies: ['_gid', '_ga*', 'nmstat', '__utma', '__utmc', '__utmz', '__utmt', '__utmb', '_hj*', 'CLID', 'SRM_B', 'uid', '_vwo*', '_gat',],
            onAccept : function(){
                updateConsentState({
                    'analytics_storage': 'granted',
                });
                // 使用沙箱内置方法推送事件
                data.pushEvent({
                    'event': 'analytics_granted',
                    'category': 'Analytics',
                    'action': 'Granted'
                });
            },
            onRevoke: function(){
                updateConsentState({
                    'analytics_storage': 'denied',
                });
            }
        },
        {
            name : 'marketing',
            label: "<strong>Marketing cookies</strong>",
            description: "<p>Marketing cookies help us show you adverts that are more relevant to you.</p>",
            cookies: ['X-AB', '_gcl*', 'uid', 'test_cookie', 'YSC', 'VISITOR_INFO1*', '_ttp', '_scid', '_scid_r', '_scid*', '_uet*', 'muc_ads', 'li_sugr', 'bcookie', 'lidc', 'personaliza*', 'MUID', 'UserMatch*', 'AnalyticsSync*', '_fbp*', '_tt_enable*', 'bscookie', 'li_gc', 'MR', 'SM', 'ANONCHK', 'MSPTC', 'IDE', 'suid', 'uid*', 'TapAd*', 'XANDR*', 'receive-cookie*', 'uuid2', '_rxuuid', 'ab', 'anHistory', 'anj', 'anProfile', 'u', 'bku', 'bkpa', '__141_cid', '__io_cid', 'A3', 'utm_*', 'NID', 'cf_clearance', '_cfuvid', '_fbc'],
            onAccept : function(){
                updateConsentState({
                    'ad_storage': 'granted',
                    'ad_user_data': 'granted',
                    'ad_personalization':'granted',
                });
                // 使用沙箱内置方法推送事件
                data.pushEvent({
                    'event': 'marketing_granted',
                    'category': 'Marketing',
                    'action': 'Granted'
                });
            },
            onRevoke: function(){
                updateConsentState({
                    'ad_storage': 'denied',
                    'ad_user_data': 'denied',
                    'ad_personalization': 'denied',
                });
            }
        }
    ],
    text: {
        title: "<div class='u-text-h4 u-font-bold u-font-serif u-mb-1'>Control your cookies</div>",
        notifyTitle: "<div class='u-text-h4 u-font-bold u-font-serif u-mb-1'>Control your cookies</div>",
        notifyText: "<p>We need some essential cookies to make this website work. We want to set other cookies to understand how you use the site and give you the best experience. If you change your mind, you can change your settings.</p>",
        acceptSettings: "Accept all",
        rejectSettings: "Reject non-essential",
        accept: "Accept all",
        reject: "Reject non-essential",
        settings: "More options",
        necessaryTitle:"<strong>Essential cookies</strong>",
        necessaryDescription:"<p>We need some essential cookies to make this website work. They help you move between pages, interact with the website and access secure areas. You can only reject essential cookies in your browser settings. Some parts of the site may not work if you do.</p>",
        closeLabel: "<span>Save and close cookie control</span>",
        notifyDescription : "<p>We need some essential cookies to make this website work. We want to set other cookies to understand how you use the site and give you the best experience.</p>",
    },
    consentCookieExpiry: 365,
    theme: 'light',
    subDomains: true,
    statement: {
        description: 'For more detailed information, please check our',
        name: 'Cookie Policy',
        url: 'https://www.mmu.ac.uk/cookie-policy',
        updated: '04/03/2024',
    },
    excludedCountries: 'all',
    position: 'left',
    layout: 'popup',
    toggleType: 'slider',
    branding: {
        'backgroundColor': '#ffffff',
        'fontColor': '#000000',
        'acceptBackground':'#ffcd00',
        'rejectBackground':'#ffffff',
        'acceptText':'#000000',
        'rejectText':'#000000',
        'removeAbout': true,
        'removeIcon': true,
        'toggleBackground':'#A9A3AD',
        'toggleText':'#ffffff',
    }
};

// end of config

const onSuccess = () => {
    const CookieControl = copyFromWindow('CookieControl');
    log(config);
    CookieControl.load(config);
    data.gtmOnSuccess();
};

const onFailure = () => {
    log("fail");
    data.gtmOnFailure();
};

injectScript('https://cc.cdn.civiccomputing.com/9/cookieControl-9.x.min.js', onSuccess, onFailure);

// Call data.gtmOnSuccess when the tag is finished.
data.gtmOnSuccess();

内容的提问来源于stack exchange,提问作者JHDT_1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 01:55:20