dargmuesli / nuxt-cookie-control

A highly configurable cookie banner for Nuxt.
MIT License
241 stars 45 forks source link

GTM Script loaded in <script> but not running #15

Closed arthurgorecki closed 1 year ago

arthurgorecki commented 1 year ago

Hello,

I am experiencing an issue with my GTM script that is unable to connect to Google Analytics. After accepting cookies, the GTM script is included in the but is not being executed. Cookies are also not being set.

I would like to know if there is any way to fix this issue or if there are additional steps I should take to establish a connection to Google Analytics.

Thank you in advance for your help.

nuxt 3 nuxt.config.ts:


export default defineNuxtConfig({
  modules: [
    '@nuxtjs/i18n',
    '@nuxtjs/robots',
    [
      '@dargmuesli/nuxt-cookie-control',
      {
        barPosition: 'bottom-right',
        colors: {
          barBackground: '#26c281',
          modalButtonBackground: '#26c281',
          checkboxActiveBackground: '#26c281',
          controlButtonIconHoverColor: '#26c281',
          controlButtonHoverBackground: '#fff',
        },
        locales: ['de'],
        cookies: {
          necessary: [
            {
              name: {
                de: 'Standard Cookies',
                en: 'Default Cookies',
              },
              description: {
                de: 'Benötigen wir zur Cookie Kontrolle',
                en: 'Default Cookies',
              },
              cookies: [
                'cookie_control_consent',
                'cookie_control_enabled_cookies',
              ],
            },
          ],

          optional: [
            {
              name: {
                en: 'Google Tag Manager',
                de: 'Google Tag Manager',
              },
              description: {
                en: 'Google Analytics is a web analytics service offered by Google that tracks and reports website traffic.',
                de: 'Google Analytics ist ein von Google angebotener Webanalysedienst, der den Website-Verkehr verfolgt und berichtet.',
              },
              initialState: false,
              src: `https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXX`,
              async: true,
              accepted: () => {
                console.log('Google GTM ENABLED. ID=G-XXXXXXX');
                window.dataLayer = window.dataLayer || [];
                function gtag(){dataLayer.push(arguments);}
                gtag('js', new Date());

                gtag('config', 'G-XXXXXXXX');
              },
              declined: () => {
                console.log('Google GTM not allowed')
              },
            },
          ],
        },
      },
    ],
    '@funken-studio/sitemap-nuxt-3',
  ],
  i18n: {
    detectBrowserLanguage: {
      useCookie: true,
      cookieKey: 'i18n_redirected',
      redirectOn: 'root',
    },

    locales: [
      {
        code: 'de',
        file: 'de.json',
        name: 'German',
        iso: 'de-DE',
      },
    ],
    lazy: true,
    langDir: 'lang/',
    defaultLocale: 'de',
    vueI18n: {
      fallbackLocale: 'de',
    },
  },

  sitemap: {
    hostname: 'https://XXXXXXXX',
    gzip: true,
  },

  robots: {
    UserAgent: '*',
    Disallow: '',
  },

  css: ['~/assets/css/main.css'],
  postcss: {
    plugins: {
      tailwindcss: {},
      autoprefixer: {},
    },
  },
  plugins: [
    { src: './plugins/Vue3-particles.ts', ssr: false },
    { src: './plugins/Vue3Lottie.client.ts', ssr: false },
  ],
})

The method from the official nuxt-cookie-control readme is also not working:

optional: [
    {
      name:  'Google Analitycs',
      //if you don't set identifier, slugified name will be used
      identifier: 'ga',
      //if multilanguage
      description: {
        en:  'Google GTM is ...'
      },
      //else
      description:  'Google GTM is...',

      initialState: true,
      src:  'https://www.googletagmanager.com/gtag/js?id=<API-KEY>',
      async:  true,
      cookies: ['_ga', '_gat', '_gid'],
      accepted: () =>{
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
          'gtm.start': new Date().getTime(),
          event: 'gtm.js'
        });
      },
      declined: () =>{
      }
    }
  ]
}
dargmuesli commented 1 year ago

Hello @arthurgorecki, thanks for checking out this repo. This repo continues the work done on nuxt-cookie-control and was published as a major release of v2 with breaking changes and Vue 3 support only. I recommend reading this repo's README and comparing the definitions in there with your code.

I see that you use cookies.(necessary|optional).cookies e.g., which is called cookies.(necessary|optional).targetCookieIds in v2. Also, the following properties do not exist anymore:

To react to cookies being accepted or declined you could watch the Cookie Control's cookiesEnabled and cookiesEnabledIds state properties instead, as they are Refs. Or, for example, to check if the user has accepted a cookie having the id: 'google-analytics' (or name: { en: 'google-analytics' }) without adding a Ref watcher you may write:

const cookieControl = useCookieControl()

if (cookieControl.cookiesEnabledIds.value.includes('google-analytics')) {
    initGoogleAnalytics() // placeholder for your custom initialization
}

src is actually still a property of cookies. I left code using src as is for v2 or at least tried to. I have not tested cookies using src though and have no case to test it for currently. If anyone could confirm if using src still works, that would be great. Personally, I use Google Analytics through vue-gtag right now. I'll post an example shortly.