Giter Site home page Giter Site logo

gtm-support / vue-gtm Goto Github PK

View Code? Open in Web Editor NEW
185.0 2.0 21.0 675 KB

Simple implementation of Google Tag Manager for Vue

Home Page: https://www.npmjs.com/package/@gtm-support/vue-gtm

License: MIT License

JavaScript 15.34% TypeScript 84.66%
gtm google googletagmanager google-tag-manager vue vue3 vue2 vuejs vuejs2 vuejs3

vue-gtm's Introduction

Vue Google Tag Manager

*** Contributors welcome ***

Google Tag Manager Vue.js

Simple implementation of Google Tag Manager in Vue.js


license: Apache-2.0 NPM package downloads code style: Prettier Build Status

This plugin will help you in your common GTM tasks.

Note: If you are looking to track all Vuex mutations, you can use Vuex GTM plugin

If you want Vue 2 compatibility, please use the package @gtm-support/vue2-gtm.

Requirements

  • Vue. >= 3.0.0
  • Google Tag Manager account. To send data to

Optional dependencies

  • Vue Router >= 4.x - In order to use auto-tracking of screens

Configuration

npm install @gtm-support/vue-gtm or yarn add @gtm-support/vue-gtm if you use Yarn package manager

Here is an example configuration:

import { createApp } from 'vue';
import { createGtm } from '@gtm-support/vue-gtm';
import router from './router';

const app = createApp(App);

app.use(router);

app.use(
  createGtm({
    id: 'GTM-xxxxxx', // Your GTM single container ID, array of container ids ['GTM-xxxxxx', 'GTM-yyyyyy'] or array of objects [{id: 'GTM-xxxxxx', queryParams: { gtm_auth: 'abc123', gtm_preview: 'env-4', gtm_cookies_win: 'x'}}, {id: 'GTM-yyyyyy', queryParams: {gtm_auth: 'abc234', gtm_preview: 'env-5', gtm_cookies_win: 'x'}}], // Your GTM single container ID or array of container ids ['GTM-xxxxxx', 'GTM-yyyyyy']
    queryParams: {
      // Add URL query string when loading gtm.js with GTM ID (required when using custom environments)
      gtm_auth: 'AB7cDEf3GHIjkl-MnOP8qr',
      gtm_preview: 'env-4',
      gtm_cookies_win: 'x',
    },
    source: 'https://customurl.com/gtm.js', // Add your own serverside GTM script
    defer: false, // Script can be set to `defer` to speed up page load at the cost of less accurate results (in case visitor leaves before script is loaded, which is unlikely but possible). Defaults to false, so the script is loaded `async` by default
    compatibility: false, // Will add `async` and `defer` to the script tag to not block requests for old browsers that do not support `async`
    nonce: '2726c7f26c', // Will add `nonce` to the script tag
    enabled: true, // defaults to true. Plugin can be disabled by setting this to false for Ex: enabled: !!GDPR_Cookie (optional)
    debug: true, // Whether or not display console logs debugs (optional)
    loadScript: true, // Whether or not to load the GTM Script (Helpful if you are including GTM manually, but need the dataLayer functionality in your components) (optional)
    vueRouter: router, // Pass the router instance to automatically sync with router (optional)
    ignoredViews: ['homepage'], // Don't trigger events for specified router names (optional)
    trackOnNextTick: false, // Whether or not call trackView in Vue.nextTick
  }),
);

This injects the tag manager script in the page, except when enabled is set to false. In that case it will be injected when calling this.$gtm.enable(true) for the first time.

Remember to enable the History Change Trigger for router changes to be sent through GTM.

Documentation

Once the configuration is completed, you can access vue gtm instance in your components like that:

export default {
  name: 'MyComponent',
  data() {
    return {
      someData: false,
    };
  },
  methods: {
    onClick() {
      this.$gtm.trackEvent({
        event: null, // Event type [default = 'interaction'] (Optional)
        category: 'Calculator',
        action: 'click',
        label: 'Home page SIP calculator',
        value: 5000,
        noninteraction: false, // Optional
      });
    },
  },
  mounted() {
    this.$gtm.trackView('MyScreenName', 'currentPath');
  },
};

The passed variables are mapped with GTM data layer as follows

dataLayer.push({
  event: event || 'interaction',
  target: category,
  action: action,
  'target-properties': label,
  value: value,
  'interaction-type': noninteraction,
  ...rest,
});

You can also access the instance anywhere whenever you imported Vue by using Vue.gtm. It is especially useful when you are in a store module or somewhere else than a component's scope.

It's also possible to send completely custom data to GTM with just pushing something manually to dataLayer:

if (this.$gtm.enabled()) {
  window.dataLayer?.push({
    event: 'myEvent',
    // further parameters
  });
}

Sync gtm with your router

Thanks to vue-router guards, you can automatically dispatch new screen views on router change! To use this feature, you just need to inject the router instance on plugin initialization.

This feature will generate the view name according to a priority rule:

  • If you defined a meta field for your route named gtm this will take the value of this field for the view name.
  • Otherwise, if the plugin don't have a value for the meta.gtm it will fallback to the internal route name.

Most of the time the second case is enough, but sometimes you want to have more control on what is sent, this is where the first rule shine.

Example:

const myRoute = {
  path: 'myRoute',
  name: 'MyRouteName',
  component: SomeComponent,
  meta: { gtm: 'MyCustomValue' },
};

This will use MyCustomValue as the view name.

Passing custom properties with page view events

If your GTM setup expects custom data to be sent as part of your page views, you can add desired properties to your route definitions via the meta.gtmAdditionalEventData property.

Example:

const myRoute = {
  path: 'myRoute',
  name: 'myRouteName',
  component: SomeComponent,
  meta: { gtmAdditionalEventData: { routeCategory: 'INFO' } },
};

This sends the property routeCategory with the value 'INFO' as part of your page view event for that route.

Note that the properties event, content-name and content-view-name are always overridden.

Passing dynamic properties with page view events

If you need to pass dynamic properties as part of your page views, you can set a callback that derives the custom data after navigation.

Example:

createGtm({
  // ...other options
  vueRouter: router,
  vueRouterAdditionalEventData: () => ({
    someComputedProperty: computeProperty(),
  }),
});

This computes and sends the property someComputedProperty as part of your page view event after every navigation.

Note that a property with the same name on route level will override this.

Using with composition API

In order to use this plugin with composition API (inside your setup method), you can just call the custom composable useGtm.

Example:

<template>
  <button @click="triggerEvent">Trigger event!</button>
</template>

<script>
import { useGtm } from '@gtm-support/vue-gtm';

export default {
  name: 'MyCustomComponent',

  setup() {
    const gtm = useGtm();

    function triggerEvent() {
      gtm.trackEvent({
        event: 'event name',
        category: 'category',
        action: 'click',
        label: 'My custom component trigger',
        value: 5000,
        noninteraction: false,
      });
    }

    return {
      triggerEvent,
    };
  },
};
</script>

Methods

Enable plugin

Check if plugin is enabled

this.$gtm.enabled();

Enable plugin

this.$gtm.enable(true);

Disable plugin

this.$gtm.enable(false);

Debug plugin

Check if plugin is in debug mode

this.$gtm.debugEnabled();

Enable debug mode

this.$gtm.debug(true);

Disable debug mode

this.$gtm.debug(false);

IE 11 support

If you really need to support browsers like IE 11, you need to configure transpileDependencies: ['@gtm-support/core'] in your vue.config.js.
See gtm-support/core#20 (comment)

Credits

vue-gtm's People

Contributors

ajuvonen avatar dependabot[bot] avatar ebisbe avatar glen-84 avatar lukahartwig avatar mehdi-1komma5grad avatar shinigami92 avatar yaquawa avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

vue-gtm's Issues

Bug: Failed to resolve entry for package "vue-router".

When I run "vite" to create my project I get these errors. What do I do wrong? Does any one know where my error is?

Info

Tool Version
Plugin v1.6.0
Vue v3.2.13
Vite v2.9.13
Node v8.13.2
OS mac

Input

// main.js

import { createApp } from "vue";
import App from "./App.vue";
import { createGtm } from "@gtm-support/vue-gtm";

import "./css/index.css";

const app = createApp(App);

app.use(
  createGtm({
    id: "GTM-xxxxxx", // Your GTM single container ID, array of container ids ['GTM-xxxxxx', 'GTM-yyyyyy'] or array of objects [{id: 'GTM-xxxxxx', queryParams: { gtm_auth: 'abc123', gtm_preview: 'env-4', gtm_cookies_win: 'x'}}, {id: 'GTM-yyyyyy', queryParams: {gtm_auth: 'abc234', gtm_preview: 'env-5', gtm_cookies_win: 'x'}}], // Your GTM single container ID or array of container ids ['GTM-xxxxxx', 'GTM-yyyyyy']
    queryParams: {
      // Add URL query string when loading gtm.js with GTM ID (required when using custom environments)
      gtm_auth: "AB7cDEf3GHIjkl-MnOP8qr",
      gtm_preview: "env-4",
      gtm_cookies_win: "x",
    },
    defer: false, // Script can be set to `defer` to speed up page load at the cost of less accurate results (in case visitor leaves before script is loaded, which is unlikely but possible). Defaults to false, so the script is loaded `async` by default
    compatibility: false, // Will add `async` and `defer` to the script tag to not block requests for old browsers that do not support `async`
    nonce: "2726c7f26c", // Will add `nonce` to the script tag
    enabled: true, // defaults to true. Plugin can be disabled by setting this to false for Ex: enabled: !!GDPR_Cookie (optional)
    debug: true, // Whether or not display console logs debugs (optional)
    loadScript: true, // Whether or not to load the GTM Script (Helpful if you are including GTM manually, but need the dataLayer functionality in your components) (optional)
    // vueRouter: router, // Pass the router instance to automatically sync with router (optional)
    ignoredViews: ["homepage"], // Don't trigger events for specified router names (optional)
    trackOnNextTick: false, // Whether or not call trackView in Vue.nextTick
  })
);

app.mount("#app");

Output or Error

✘ [ERROR] [plugin vite:dep-pre-bundle] Failed to resolve entry for package "vue-router". The package may have incorrect main/module/exports specified in its package.json: No known conditions for "." entry in "vue-router" package

    node_modules/vite/dist/node/chunks/dep-80fe9c6b.js:40945:10:
      40945 │     throw new Error(`Failed to resolve entry for package "${id}". ` +
            ╵           ^

    at packageEntryFailure (/Users/ob/Data/node_modules/vite/dist/node/chunks/dep-80fe9c6b.js:40945:11)
    at resolvePackageEntry (/Users/ob/Data/node_modules/vite/dist/node/chunks/dep-80fe9c6b.js:40941:9)
    at tryNodeResolve (/Users/ob/Data/node_modules/vite/dist/node/chunks/dep-80fe9c6b.js:40748:20)
    at Context.resolveId (/Users/ob/Data/node_modules/vite/dist/node/chunks/dep-80fe9c6b.js:40556:28)
    at Object.resolveId (/Users/ob/Data/node_modules/vite/dist/node/chunks/dep-80fe9c6b.js:39229:55)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async /Users/ob/Data/node_modules/vite/dist/node/chunks/dep-80fe9c6b.js:61552:27
    at async /Users/ob/Data/node_modules/vite/dist/node/chunks/dep-80fe9c6b.js:38746:34
    at async callback (/Users/ob/Data/node_modules/esbuild/lib/main.js:921:28)
    at async handleRequest (/Users/ob/Data/node_modules/esbuild/lib/main.js:701:30)

  This error came from the "onResolve" callback registered here:

    node_modules/vite/dist/node/chunks/dep-80fe9c6b.js:38725:18:
      38725 │             build.onResolve({ filter: /^[\w@][^:]/ }, async ({ path: id, importer, kind }) => {
            ╵                   ~~~~~~~~~

    at setup (/Users/ob/Data/node_modules/vite/dist/node/chunks/dep-80fe9c6b.js:38725:19)
    at handlePlugins (/Users/ob/Data/node_modules/esbuild/lib/main.js:843:23)
    at Object.buildOrServe (/Users/ob/Data/node_modules/esbuild/lib/main.js:1137:7)
    at /Users/ob/Data/node_modules/esbuild/lib/main.js:2085:17
    at new Promise (<anonymous>)
    at Object.build (/Users/ob/Data/node_modules/esbuild/lib/main.js:2084:14)
    at Object.build (/Users/ob/Data/node_modules/esbuild/lib/main.js:1931:51)
    at runOptimizeDeps (/Users/ob/Data/node_modules/vite/dist/node/chunks/dep-80fe9c6b.js:39969:34)
    at async runOptimizer (/Users/ob/Data/node_modules/vite/dist/node/chunks/dep-80fe9c6b.js:50498:38)

  The plugin "vite:dep-pre-bundle" was triggered by this import

    node_modules/@gtm-support/vue-gtm/dist/index.js:116:93:
      116 │                     return [4 /*yield*/, Promise.resolve().then(function () { return require('vue-router'); })];
          ╵                                                                                              ~~~~~~~~~~~~

3:08:40 PM [vite] error while updating dependencies:
Error: Build failed with 1 error:
node_modules/vite/dist/node/chunks/dep-80fe9c6b.js:40945:10: ERROR: [plugin: vite:dep-pre-bundle] Failed to resolve entry for package "vue-router". The package may have incorrect main/module/exports specified in its package.json: No known conditions for "." entry in "vue-router" package
    at failureErrorWithLog (/Users/ob/Data/node_modules/esbuild/lib/main.js:1605:15)
    at /Users/ob/Data/node_modules/esbuild/lib/main.js:1251:28
    at runOnEndCallbacks (/Users/ob/Data/node_modules/esbuild/lib/main.js:1034:63)
    at buildResponseToResult (/Users/ob/Data/node_modules/esbuild/lib/main.js:1249:7)
    at /Users/ob/Data/node_modules/esbuild/lib/main.js:1358:14
    at /Users/ob/Data/node_modules/esbuild/lib/main.js:666:9
    at handleIncomingPacket (/Users/ob/Data/node_modules/esbuild/lib/main.js:763:9)
    at Socket.readFromStdout (/Users/ob/Data/node_modules/esbuild/lib/main.js:632:7)
    at Socket.emit (node:events:527:28)
    at addChunk (node:internal/streams/readable:315:12)
Vite Error, /node_modules/.vite/deps/@gtm-support_vue-gtm.js?v=06a117ea optimized info should be defined
Vite Error, /node_modules/.vite/deps/@gtm-support_vue-gtm.js?v=06a117ea optimized info should be defined (x2)

Tanks
Oliver

Dynamically setting additional properties on route change

Request / Idea

Allow meta.gtmAdditionalEventData to be dynamically resolved whenever router.afterEach is called. This could be done for example by allowing gtmAdditionalEventData to be a function or by adding a callback to the options that is called to resolve gtmAdditionalEventData.

Additional Context

Currently additional properties can be set on a per route basis with meta.gtmAdditionalEventData. I would like to read these properties from the vuex store when the route changes because the data changes over time.

Multiple GTM containers in vue throws errors in production

I am able to add multiple ids in the id array and it loads well and properly adds the script on local
However, when the code makes it to production, it throws invalid errors because the IDs are getting concatenated(probably due to minified files, not sure). How can I fix this?

Pictures of local and deployed version are attached

Screen Shot 2022-07-28 at 2 54 41 PM

Screen Shot 2022-07-28 at 2 56 48 PM

Scroll tracking on every view

Hello, guys!

First of all, thanks for building this plugin!

I'm building a SPA using it and I've managed to track all page views correctly, but I've noticed that the "scroll" event is only fired once and this is due to gtag only tracking scroll once per page load. Since there are no full page loads after the first one on a SPA, scroll tracking doesn't work properly.

As a workaround, I've found this GTM recipe that basically includes tags that tracks scroll behavior and allows you to reset the scroll tracking every time the view changes.

It would be very nice to have all of this integrated into vue-gtm.

Add ability to load local gtm.js

Request / Idea

Google Chrome Extension Manifest v3 blocks loading external scripts, even their own. In this case, this implementation no longer works as the content security policy throws an error with: https://www.googletagmanager.com/gtm.js

The solution is to add the ability to load local gtm.js or include gtm.js into this package with an optional flag.

Additional Context

More here: https://groups.google.com/a/chromium.org/g/chromium-extensions/c/0mPEDNJA0XM?pli=1

SSR support?

Request / Idea

Inject the needed scripts (in the head and body tag) in SSR, so the server wil render the tags.

Additional Context

Use https://github.com/vueuse/head to inject script to the head tag.

Of course this needs some work in the frontend, because you have to get the injected head and merge with your index.html, see: https://github.com/vueuse/head#ssr-rendering

There seems no plugin available to inject stuff into the body, as Evan You states: You should not teleport an element to the body because SSR don't know how to hydrate it. Maybe exposing a function, returning the code to add to the body, and implement it in the SSR implementation live mentioned in the vueuse link.

Im going to need this, so expect a PR soon!

Filter internal traffic by IP address

I'm trying to filter our our internal traffic by IP address. I've setup the appropriate filters in Google Analytics data streams/settings.

It seems like the user's IP address is not being passed from GTM to GA4.

Has anyone experienced this or have any insights?

Accessing the gtm instance outsite of a component

Hi,

In the docs, it says: You can also access the instance anywhere whenever you imported Vue by using Vue.gtm. It is especially useful when you are in a store module or somewhere else than a component's scope.

But in vue 3, you can't use

import  Vue from 'vue'

How can I access gtm outside of a component? Could you give an example, especially what to import in a js file with Vue 3? I'm trying to access it in a separated js file (helper).


Edit: I guess I found It. First I need to export app from main.js, then import it into a js file to consume.

main.js:

import { createApp } from 'vue'
import App from '@/App.vue'
...
const app = createApp(App)
...

// this is the key
export default app

helper.js:

import app from '@/main'

console.log(app.config.globalProperties.$gtm)

If my way is correct, could you update the docs?

Thank you!

Documentation improvement: gtmAdditionalEventData

Request / Idea: Improved documentation for route.meta.gtmAdditionalEventData

Adding extra properties to page view events is not documented, but support for it exists. By defining meta.gtmAdditionalEventData for a route, you can have additional properties sent along with the event. For our project this was an important discovery because we distinguish events from different environments through an additional property.

If this feature is not deprecated, I request that you improve the README.md regarding the proper use of this feature.

Additional Context

const additionalEventData: Record<string, any> = (to.meta?.gtmAdditionalEventData as Record<string, any>) ?? {};

https://github.com/gtm-support/core/blob/687524ae88b6efa11644181f6709799dce713726/src/gtm-support.ts#L161

How to properly access `cid` value ?

Request / Idea

In the case of our app, we need to access the cid value from analytics.
For now we found a workaround by accessing cookies _ga and replacing GA1.1.:

const cid = cookies.get('_ga').replace('GA1.1.', '');

Probably there is a better way to do it, do you know where I can access this value using the library or maybe on window instance ?

Nuxt support

Request / Idea

Hi, this is a very nice tool. I wonder do you consider to support Nuxt.js? The origional @nuxt/gtm never worked for me, so it would be great if vue-gtm can support nuxt. Many thanks!
...

Additional Context

...

Nonce not added as attribute

This plugin does not apply the nonce attribute to the gtm script tag. when inspecting the script element in chrome I can see no nonce value added to the attributes list, however it is there as a property.

This is the following error breaking our CSP.

The source list for the Content Security Policy directive 'script-src' contains an invalid source: ''nonce-{{nonce}}''. It will be ignored.

Here is my implementation, is there a work around or fix ?


`import { createGtm, useGtm } from '@gtm-support/vue-gtm'
import analyticsFactory from '~/services/analytics/analyticsFactory'

export default defineNuxtPlugin((nuxtApp) => {
  const config = useRuntimeConfig()
  const nonce = useNonce()

  nuxtApp.vueApp.use(
    createGtm({
      id: 'XXXXXXXXXXX',
      enabled: true,
      nonce
    })
  )

  return {
    provide: {
      gtm: useGtm(),
      dataLayer: analyticsFactory()
    }
  }
})`

Bug: cannot use without vue-route

Info

Tool Version
vue-gtm v1.6.0
Vue v3.2.37
OS linux

Input

import {createApp, h} from 'vue';
import {createInertiaApp} from '@inertiajs/inertia-vue3';
import {InertiaProgress} from '@inertiajs/progress';
import {VueReCaptcha} from 'vue-recaptcha-v3'
import {createGtm} from '@gtm-support/vue-gtm';

createInertiaApp({
    title: (title) => `${title} - ${appName}`,
    resolve: (name) => require(`./Pages/${name}.vue`),
    setup({el, app, props, plugin}) {
        const captchaKey = props.initialPage.props.recaptcha_site_key;
        return createApp({render: () => h(app, props)})
            .use(plugin)
            .use(VueReCaptcha, {
                siteKey: captchaKey, badge: 'inline',
                size: 'invisible'
            })
        app.use(
            createGtm({
                id: 'GTM-xxxxxx',
                queryParams: {
                    gtm_auth: 'AB7cDEf3GHIjkl-MnOP8qr',
                    gtm_preview: 'env-4',
                    gtm_cookies_win: 'x',
                },
            }),
        )
            .mixin({methods: {route}})
            .mount(el);
    },
});

Output or Error

ERROR in ./node_modules/@gtm-support/vue-gtm/dist/index.js 116:85-106
Module not found: Error: Package path . is not exported from package /var/www/html/node_modules/vue-router (see exports field in /var/www/html/node_modules/vue-router/package.json)    

webpack compiled with 1 error

Additional Context

I just installed it on Vue3 I don't have vue-router and I'm not going to use it.

Bug: router can not be passed to the plugin because the corresponding property doesn

Info

Tool Version
Plugin v2.2.0
Vue v3.0.0
Node v18.7.1
OS mac

Input

app.use(
  createGtm({
    id: 'GTM-xxxxxx', 
   vueRouter: router
 

Output or Error

Property 'vouRouter' doesn't exist.

Expected Output

// nothing

Additional Context

The README states how to pass the router to the plugin. However, the mentioned property doesn't exists.
How to do that?

How to add content_group

Request / Idea

Is it possible to add countent_group to the request? So foe example I can add different groups per page.

thank you
...

Additional Context

...

Google Tag Manager tag is not firing when viewing the page; we have to reload the pageBug:

Info

Tool Version
Plugin v2
Vue v2.6.12
Node v14
OS mac

Input

Configure it in main.js

  import VueGtm from '@gtm-support/vue2-gtm';
  export default function(Vue, { router, head, isClient }) {
  
      if( process.isClient){
          Vue.use(VueGtm, {
              id: 'GTM-PR7VTQG',
              vueRouter: router,
              enabled: true,
              debug: true,
          });
      }
    }
    

Configure it in my component

export default {
   name: "WpPage",
   components: {
     BlockBase: () => import('../components/BlockBase.vue'),
     MetaInfo: () => import('../components/MetaInfo.vue'),
     EventsCollective: () => import('../components/EventsCollective.vue'),
     NewsCollective: () => import('../components/NewsCollective.vue'),
     ArchivedEvents: () => import('../components/ArchivedEvents.vue'),
   },
   mounted() {
     var mainTitle = this.$page.wpPage.title;
     this.$gtm.trackView(mainTitle, window.location.pathname)
   },
 };  

Output or Error

GTM tag is not firing the website

Expected Output

I am expecting GTM to fire the website.

Additional Context

I'm using Gridsome to build my website. When trying to build with Vue GTM module Google Tag Manager tag is not firing when viewing the page so we have to reload the page. I think because this is a third-party service, it only renders itself once per page load.?

Bug: You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.Because the code uses the null merge operator (??)

Info

Tool Version
Plugin ^2.0.0
Vue v2.x.x
Node 14.17.0
OS win

Input

const baseUrl = vueRouter.options.base ?? ""

Output or Error

You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders

Expected Output

Additional Context

in my nuxt project,npm run in vscode,It seems that the null value merge operator (??) is used。Previous versions using ^ 1.3.0 will not look like this

【error】
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders

 const baseUrl = vueRouter.options.base ?? ""

@ ./plugins/gtm.ts 2:0-43 6:10-16

Bug: nonce config does not output nonce to script tag

Info

Tool Version
Plugin v2.0.0
Vue v3.2.47
Node v16.19.0
OS mac

Input

createGtm({
    id: 'GTM-XXXXXXX',
    enabled: true,
    loadScript: true,
    vueRouter: router,
    nonce: '2726c7f26c',
})

Output or Error

Nonce is not output into Script tag

Expected Output

nonce should be added to script tag created by the package

Additional Context

It looks like the nonce setting does not work, setting this to any value does not result in the nonce being output in the script tag generated by the package.

This also seems to be the same for the defer config value. Making defer true does not add defer to the script

Bug: Module pushes events to the datalayer that are empty with the name "interaction"

Info

Tool Version
Plugin v2.1.0
Vue v3.3.4
Node v18.17.1
OS win

Output or Error

Something in the plugin/module pushes "event: 'interaction'" to the datalayer. We are not running something that could potentially send this, so it looks like it is the module itself.

Expected Output

I expect no unexpected pushes.

Additional Context

We are running this with nuxt3.

Bug: ReferenceError: document is not defined

Info

Tool Version
Plugin v1.2.2
Vue 3.2.20
Node v17.0.1
OS mac

Input

Output or Error

Expected Output

Additional Context

When building the project with vite-ssg you are prerendering every page. There's no document so it crashes when building it for every page.

It's the same issue it happened henk-badenhorst/vue-hotjar-next#11 and the same solution should work.

Add if (typeof window === 'undefined') return previous to line to avoid calling the loadScript() function.

Bug: The GTM Tag ID shows as "G-XXXXXXX", "UA-XXXXXX" or "AW-XXXXXXX" not GTM-XXXXXX

Info

Tool Version
Plugin v2.2.0
Vue v3.3.4
Node v18.3.0
OS win

Input

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import { createGtm } from '@gtm-support/vue-gtm';
const app = createApp(App)
app.use(router)
app.use(
    createGtm({
        id: 'AW-XXXXXXXXX', // Your GTM single container ID, array of container ids ['GTM-xxxxxx', 'GTM-yyyyyy'] or array of objects [{id: 'GTM-xxxxxx', queryParams: { gtm_auth: 'abc123', gtm_preview: 'env-4', gtm_cookies_win: 'x'}}, {id: 'GTM-yyyyyy', queryParams: {gtm_auth: 'abc234', gtm_preview: 'env-5', gtm_cookies_win: 'x'}}], // Your GTM single container ID or array of container ids ['GTM-xxxxxx', 'GTM-yyyyyy']
        queryParams: {
            // Add URL query string when loading gtm.js with GTM ID (required when using custom environments)
            // gtm_auth: 'AB7cDEf3GHIjkl-MnOP8qr',
            // gtm_preview: 'env-4',
            // gtm_cookies_win: 'x',
        },
        //source: 'https://customurl.com/gtm.js', // Add your own serverside GTM script
        defer: false, // Script can be set to `defer` to speed up page load at the cost of less accurate results (in case visitor leaves before script is loaded, which is unlikely but possible). Defaults to false, so the script is loaded `async` by default
        compatibility: false, // Will add `async` and `defer` to the script tag to not block requests for old browsers that do not support `async`
        nonce: '7646c7f45a', // Will add `nonce` to the script tag
        enabled: false, // defaults to true. Plugin can be disabled by setting this to false for Ex: enabled: !!GDPR_Cookie (optional)
        debug: false, // Whether or not display console logs debugs (optional)
        loadScript: true, // Whether or not to load the GTM Script (Helpful if you are including GTM manually, but need the dataLayer functionality in your components) (optional)
        vueRouter: router, // Pass the router instance to automatically sync with router (optional)
        //ignoredViews: ['homepage'], // Don't trigger events for specified router names (optional)
        trackOnNextTick: false, // Whether or not call trackView in Vue.nextTick
    }),
);

app.mount('#app')

Output or Error

The app and plugin are not working

Uncaught Error: 'AW-XXXXXXXXX' is not a valid GTM-ID (/^GTM-[0-9A-Z]+$/). Did you mean 'GTM-645401673'?

Expected Output

Working application and plugin

Additional Context

Bug: vue-router in createGtm has unnecessary type, "listening"

Info

Tool Version
Plugin v1.6.0
Vue v4.0.12
Vue-Router v3.2.31
Node v16.15.0
OS win(WSL)

Input

Vue Router has type error

createGtm({
      id: 'GTM-xxxxxx', // Your GTM single container ID, array of container ids ['GTM-xxxxxx', 'GTM-yyyyyy'] or array of objects [{id: 'GTM-xxxxxx', queryParams: { gtm_auth: 'abc123', gtm_preview: 'env-4', gtm_cookies_win: 'x'}}, {id: 'GTM-yyyyyy', queryParams: {gtm_auth: 'abc234', gtm_preview: 'env-5', gtm_cookies_win: 'x'}}], // Your GTM single container ID or array of container ids ['GTM-xxxxxx', 'GTM-yyyyyy']
      defer: false, // Script can be set to `defer` to speed up page load at the cost of less accurate results (in case visitor leaves before script is loaded, which is unlikely but possible). Defaults to false, so the script is loaded `async` by default
      compatibility: false, // Will add `async` and `defer` to the script tag to not block requests for old browsers that do not support `async`
      nonce: '2726c7f26c', // Will add `nonce` to the script tag
      enabled: true, // defaults to true. Plugin can be disabled by setting this to false for Ex: enabled: !!GDPR_Cookie (optional)
      debug: true, // Whether or not display console logs debugs (optional)
      loadScript: true, // Whether or not to load the GTM Script (Helpful if you are including GTM manually, but need the dataLayer functionality in your components) (optional)
      vueRouter: router, // Pass the router instance to automatically sync with router (optional)
      ignoredViews: ['homepage'], // Don't trigger events for specified router names (optional)
      trackOnNextTick: false, // Whether or not call trackView in Vue.nextTick
    })

Output or Error

TS2741: Property 'listening' is missing in type 'import(".../node_modules/vue-router/dist/vue-router").Router' but required in type 'import(".../node_modules/@gtm-support/vue-gtm/node_modules/vue-router/dist/vue-router").Router'.

Expected Output

no type error

Additional Context

Bug: ID from Google Analytics 4 doesn't work

Info

Tool Version
Plugin v2.x.x
Vue v2.x.x

The ID generated on Google Analytics 4 is not supported because the ID starts only with G and the regex that validates the ID only supports ID starting with GTM

Input

Environment variable
VUE_APP_GTM_ID=G-XXXXXXXXX

Vue.use(VueGtm, {
  id: process.env.VUE_APP_GTM_ID,
  vueRouter: router
});

Output or Error

Uncaught Error: 'G-XXXXXXXXX' is not a valid GTM-ID (/^GTM-[0-9A-Z]+$/). Did you mean 'GTM-XXXXXXXXX'?

A way to opt out after createGtm

Request / Idea

I would like to be able to configure the user to not send any information from the application.
To do this, we need to prevent sending data to GTM in some way.

Currently, vue-gtm can be opted out by setting enable of createGtm to false, but this requires the user to reload once.
I would like to have a way to delay opting out by code without reloading.

Additional Context

VOICEVOX/voicevox#497

Problems wit Google consent mode v2

I might be that I am just incredibly stupid but how can i get consent mode v2 working with this package?

I am quite new to Google analytics and tag manager and would need to add the new ad personalisation consent signals that are required for GA4 in the European Economic Area.

Or is this just the wrong tool for the job?

Any help is highly appreciated.

Using in Nuxt 3 project. `page_view` works, but `trackEvent` doesn't

I'm using @gtm-support/vue-gtm in Nuxt 3 App

Info

Tool Version
Plugin v2.0.0
Vue v3.2.45

vue-gtm.client.js:

import { createGtm } from '@gtm-support/vue-gtm'

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.use(createGtm({
    id: 'XXX-XXXXXXX',
    defer: false,
    compatibility: false,
    enabled: true,
    debug: true,
    loadScript: true,
    vueRouter: useRouter(),
    trackOnNextTick: false
  }))
})

Then page_view works. Then I try use trackEvent in the setup:

composables/useGTM.js:

import { useGtm as useVueGtm } from '@gtm-support/vue-gtm'

export default () => {
  const gtm = useVueGtm()
  return gtm;
}

myComponent.vue:

const $gtm = useGTM();
$gtm.trackEvent({
  event: 'add_to_cart',
  category: 'ecommerce',
  action: 'click',
  label: 'Adding item to cart',
  value: 5000,
  noninteraction: false,
})

When I'm adding item to cart nothing's happened in the Googlу Analytics. There is also no new request in the "Network". But in the console I see

[GTM-Support]: Dispatching event {event: 'add_to_cart', category: 'ecommerce', action: 'click', label: 'Adding item to cart', value: 5000}

What am I doing wrong?

Show a warning instead of throwing an error on invalid GTM ID

Info

App won't start if an invalid GTM ID is used in my setup (which, I believe, is a pretty standard setup).

Tool Version
Plugin v1.0.0 (Vue2)
Vue v2.6.12
Node v14.15.5
OS Ubuntu 20.04.2 LTS

Input

import Vue from "vue";
import App from "./App.vue";
import VueGtm from "@gtm-support/vue2-gtm";

Vue.use(VueGtm, {
  id: "INVALID"
});

new Vue({
  render: (h) => h(App)
}).$mount("#app");

Output or Error

Crash screen with error report on codesandbox.io or Console.error and a blank screen in localhost:

assert-is-gtm-id.js:15 Uncaught Error: GTM-ID 'INVALID' is not valid
    at Object.assertIsGtmId (assert-is-gtm-id.js:15)
    at new GtmSupport (gtm-support.js:35)
    at Object.install (index.js:29)
    at Function.Vue.use (vue.esm.js:5116)
    at Module../src/main.js (main.js:37)
    at __webpack_require__ (bootstrap:769)
    at fn (bootstrap:129)
    at Object.0 (app.js:136081)
    at __webpack_require__ (bootstrap:769)
    at bootstrap:907

Expected Output

I would expect a console warning Your are using an invalid GTM ID and the app should load but without GTM.

Additional Context

TryCatch gets around the issue and so does using a valid GTM ID obviously ;-) but for those cases where an ID is fat fingered into an environment variable for example I would expect the plugin to catch and handle it's own error.

try {
  Vue.use(VueGtm, {
    id: 'INVALID',
    vueRouter: router
  })
} catch (error) {
  console.warn(error)
}

Bug: Module not found: Error: Package path . is not exported from package

Info

Tool Version
Vue v3.2.37
vue-router v4.1.1
vue-gtm v1.6.0
OS mac

Input

import { createApp } from "vue";
import App from "@/App.vue";
import router from "@/router";
import store from "@/store.js";
import { createGtm } from "@gtm-support/vue-gtm";

createApp(App)
  .use(router)
  .use(store)
  .use(
    createGtm({
      id:<ID>,
      source: <GTM_SCRIPT_URL>,
      vueRouter: router,
    })
  )
  .mount("#app");

Output or Error

ERROR  Failed to compile with 1 error 
error  in ./node_modules/@gtm-support/vue-gtm/dist/index.js
Module not found: Error: Package path . is not exported from package /Users/.../node_modules/vue-router (see exports field in /Users/.../node_modules/vue-router/package.json)

ERROR in ./node_modules/@gtm-support/vue-gtm/dist/index.js 116:85-106
Module not found: Error: Package path . is not exported from package /Users/.../node_modules/vue-router (see exports field in /Users/.../node_modules/vue-router/package.json)
 @ ./src/main.js 5:0-49 14:8-17

webpack compiled with 1 error

Additional Context

Moved frm vue2 to vue3. tried "@gtm-support/vue-gtm": "^1.6.0", but get this error

Error: Module parse failed: @gtm-support/core/lib/gtm-support.js Unexpected token (45:12)

Hi,

Thanks for great package. I have tried to use it in one of Vue 2 application but I got the below 3 compile errors for 'npm run prod'

Module parse failed: LOCAL DIRECTORY/@gtm-support/core/lib/gtm-support.js Unexpected token (45:12)
You may need an appropriate loader to handle this file type.
|             defer: false,
|             compatibility: false,
|             ...options,
|         };
|         // @ts-expect-error: Just remove the id from options

 @ ./~/@gtm-support/core/lib/index.js 7:20-44
 @ ./~/@gtm-support/vue2-gtm/dist/index.js
 @ ./resources/assets/PROJ/app.js
 @ multi ./resources/assets/PROJ/js/md-snackbars.js ./resources/assets/PROJ/js/spark.js ./resources/assets/PROJ/app.js

 error  in ./~/@gtm-support/core/lib/utils.js

Module parse failed: LOCAL DIRECTORY/node_modules/@gtm-support/core/lib/utils.js Unexpected token (37:8)
You may need an appropriate loader to handle this file type.
|     const queryString = new URLSearchParams({
|         id,
|         ...((_c = config.queryParams) !== null && _c !== void 0 ? _c : {}),
|     });
|     const source = (_d = config.source) !== null && _d !== void 0 ? _d : 'https://www.googletagmanager.com/gtm.js';

 @ ./~/@gtm-support/core/lib/index.js 9:14-32
 @ ./~/@gtm-support/vue2-gtm/dist/index.js
 @ ./resources/assets/PROJ/app.js
 @ multi ./resources/assets/PROJ/js/md-snackbars.js ./resources/assets/PROJ/js/spark.js ./resources/assets/PROJ/app.js

 error  

/assets/js/PROJ.js from UglifyJs
Unexpected character '`' [./~/@gtm-support/core/lib/assert-is-gtm-id.js:15,0][/assets/js/PROJ.js:100804,24]

package json

{
  "private": true,
  "devDependencies": {
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-stage-2": "^6.24.1",
    "laravel-mix": "0.10.0",
    "pusher-js": "^4.2.2",
    "vue-template-compiler": "^2.5.13",
    "vuetable-2": "^1.7.2",
    "webpack": "^2.7.0",
    "webpack-cli": "3.3.0"
  },
  "dependencies": {
    "@gtm-support/vue2-gtm": "^1.3.0",
    "accounting": "^0.4.1",
    "axios": "^0.15.3",
    "chart.js": "^2.9.1",
    "child_process": "^1.0.2",
    "express": "^4.16.2",
    "fs": "^0.0.1-security",
    "ioredis": "^2.5.0",
    "jquery": "^3.3.1",
    "laravel-echo": "^1.3.4",
    "lodash": "^4.16.2",
    "moment-countdown": "0.0.3",
    "moment-timezone": "^0.5.27",
    "net": "^1.0.2",
    "tls": "0.0.1",
    "underscore": "^1.10.2",
    "vee-validate": "^2.0.3",
    "vue": "^2.5.13",
    "vue-bootstrap-typeahead": "^0.2.6",
    "vue-events": "^3.1.0",
    "vue-gmaps": "^0.2.2",
    "vue-i18n": "^8.15.0",
    "vue-js-modal": "^2.0.1",
    "vue-quill-editor": "^2.3.3",
    "vue-router": "2.3.0",
    "vue-sweetalert": "^0.1.18",
    "vue-tables-2": "^0.6.99",
    "vue-tel-input": "^5.0.4",
    "vue-typer": "^1.2.0",
    "vue2-dropzone": "^2.3.6"
  }
}

Any idea what might be issue here?. Thanks in advance.

Bug: Plugin is not working with stream ID

Info

Tool Version
Plugin v1.3.0
Vue v2.7
Node v16.10.0
OS win

Input

I am using your plugin like this:
image
I am using this information I got from Google Analytics:
image
The measurement ID I am using as an ID is: G-G1HQXCMMVY

Output or Error

I am getting an error with the page and it doesn't load anything:
image

What is the right ID to use to make the plugin works?

Google Analytics 4 support?

Request / Idea

Is Google Analytics 4 supported yet? Any plans to do that? The old support runs out 1. Juli 2023

Bug: My GTM tag starts with G instead of GTM

Info

Tool Version
Plugin v2.0.0
Vue v3.2.45
Node v18.12.1
OS mac

Input

app.use(
    createGtm({
      id: 'G-XXXX,
      queryParams: {
        gtm_auth: 'AB7cDEf3GHIjkl-MnOP8qr',
        gtm_preview: 'env-4',
        gtm_cookies_win: 'x',
      },
      defer: false,
      compatibility: false,
      nonce: '2726c7f26c',
      enabled: true,
      vueRouter: router,
    }),
  );

Output or Error

index.js:6 Uncaught Error: 'G-F7Q3NEJYHL' is not a valid GTM-ID (/^GTM-[0-9A-Z]+$/). Did you mean 'GTM-F7Q3NEJYHL'?
    at assertIsGtmId (index.js:6:11)
    at new GtmSupport (index.js:66:7)
    at install (index.js:7:15)
    at Object.install (index.js:90:30)
    at Object.use (runtime-core.esm-bundler.js:4381:28)
    at initGTM (vueGTM.js?t=1675611482495:4:7)
    at main.js?t=1675611482495:16:1

Expected Output

Should work as expected.

Additional Context

I created new google analytics account and google gave me a tag that starts with G-xxx or GT-xxx. When I init plugin with this new tag, plugin gives error but should work as expected. Also, google suggest me to use https://www.googletagmanager.com/gtag/js? instead of plugin uses https://www.googletagmanager.com/gtm.js. I think google made changes on script and tags so, we should adopt plugin to new changes.

Bug: Support for Vue 2.7.x (peerDependency warning)

Info

Tool Version
Plugin v1.3.0
Vue v2.7.10
Node v18.9.0
OS win

Input

"node_modules/@gtm-support/vue2-gtm": {
      "version": "1.3.0",
      "resolved": "https://registry.npmjs.org/@gtm-support/vue2-gtm/-/vue2-gtm-1.3.0.tgz",
      "integrity": "sha512-yO7+gxSQEEcPH6gWMNcdhRDyj4ApBnG4JHIizP1HfY8y1+8SFNQIWE1icJY8l3wNW6DYVz3wtP+Ri2Wk4aF7Kw==",
      "dependencies": {
        "@gtm-support/core": "1.3.0"
      },
      "peerDependencies": {
        "vue": "^2.6.14"
      }
}

Output or Error

npm WARN ERESOLVE overriding peer dependency
npm WARN While resolving: @vue/[email protected]
npm WARN Found: [email protected]
npm WARN node_modules/vue
npm WARN   peer vue@"^2.6.14" from @gtm-support/[email protected]
npm WARN   node_modules/@gtm-support/vue2-gtm
npm WARN     @gtm-support/vue2-gtm@"^1.3.0" from the root project 

Getting this warning when updating Vue from 2.6 to 2.7.10.

Bug: cannot install with vue@^3.2.0

Info

Tool Version
Plugin v2.0.0
Vue v3.2.0
Node v18
OS mac

Input

npm install

Output or Error

npm ERR! Could not resolve dependency:
npm ERR! @gtm-support/vue-gtm@"^2.0.0" from the root project
npm ERR! 
npm ERR! Conflicting peer dependency: [email protected]
npm ERR! node_modules/vue
npm ERR!   peer vue@"^3.2.0" from @gtm-support/[email protected]
npm ERR!   node_modules/@gtm-support/vue-gtm
npm ERR!     @gtm-support/vue-gtm@"^2.0.0" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! 
npm ERR! See /home/node/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/node/.npm/_logs/2023-03-03T21_14_33_526Z-debug-0.log

Expected Output

Additional Context

I am migrating a Vue2 repo to Vue3 and I currently have my vue package version set to ^3.2.0 and @gtm-support/vue-gtm set to ^2.0.0.

When I run npm install I receive the error seen above. In the package.json if your repo you list a devDep for vue at ^3.2.40 and a peerDep at ^3.2.0. I have to set my vue version to ^3.2.40 to avoid the error.

1.2 vue3 dont work without vue-router

version 1.1 works without having vue-router as dep in project.
Version 1.2 dont work anymore without vue-router

vue-tsc --noEmit && vite build

node_modules/.pnpm/registry.npmjs.org+@[email protected][email protected]/node_modules/@gtm-support/vue-gtm/dist/index.d.ts:4:54 - error TS2307: Cannot find module 'vue-router' or its corresponding type declarations.

4 import type { RouteLocationNormalized, Router } from 'vue-router';

PartyTown support

Request / Idea

Page speed insights is complaining about Google Analytics module blocking the main thread. I figured that Partytown web worker can help avoid blocking the main thread when using analytics.

Is there any chance it could be supported out of the box?

Additional Context

Adding a new property to tell the set up to use partytown.
https://partytown.builder.io

Error : You may need an appropriate loader to handle this file type

I am using @gtm-support/vue2-gtm": "^1.0.0" in one of my Vue-2 applications and the Vue versions are as follows:


    "vue": "^2.5.2",
    "vue-cookies": "^1.5.4",
    "vue-i18n": "^8.0.0",
    "vue-recaptcha": "^1.1.1",
    "vue-router": "^3.0.1",
    "vue-scrollto": "^2.17.1",
    "vue-session": "^1.0.0",
    "vuex": "^3.0.1"

and for the Webpack and Vue-Loader :

  "babel-core": "^6.22.1",
  "babel-eslint": "^7.2.3",
  "babel-loader": "^7.1.1",
  "dotenv-webpack": "^4.0.0",
  "vue-loader": "^13.3.0",
  "webpack": "^3.6.0",
  "webpack-bundle-analyzer": "^2.9.0",
  "webpack-dev-server": "^2.9.1",
  "webpack-hot-middleware": "^2.22.3",
  "webpack-merge": "^4.1.0"

Now, when I start my application, I get the following error:

ERROR  Failed to compile with 2 errors                                                                                                                                                                                                                                3:45:02 PM

 error  in ./node_modules/@gtm-support/core/lib/utils.js

Module parse failed: Unexpected token (30:8)
You may need an appropriate loader to handle this file type.
|     const queryString = new URLSearchParams({
|         id,
|         ...((_c = config.queryParams) !== null && _c !== void 0 ? _c : {})
|     });
|     script.src = `https://www.googletagmanager.com/gtm.js?${queryString}`;

 @ ./node_modules/@gtm-support/core/lib/index.js 9:14-32
 @ ./node_modules/@gtm-support/vue2-gtm/dist/index.js
 @ ./src/main.js
 @ multi (webpack)-dev-server/client?http://localhost:8002 webpack/hot/dev-server ./src/main.js

 error  in ./node_modules/@gtm-support/core/lib/gtm-support.js

Module parse failed: Unexpected token (44:12)
You may need an appropriate loader to handle this file type.
|             defer: false,
|             compatibility: false,
|             ...options
|         };
|         // @ts-expect-error: Just remove the id from options

 @ ./node_modules/@gtm-support/core/lib/index.js 7:20-44
 @ ./node_modules/@gtm-support/vue2-gtm/dist/index.js
 @ ./src/main.js
 @ multi (webpack)-dev-server/client?http://localhost:8002 webpack/hot/dev-server ./src/main.js

In the main.js file. I have the following code:

import VueGtm from '@gtm-support/vue2-gtm'

Vue.use(VueGtm, {
  id: 'GTM-IDXX',
  defer: false,
  enabled: true,
  debug: true,
  loadScript: true
}) 

And I have a util.js file, and there I have the function for tracking events:

export default submitGTMEvents = (category, action, label) => {
  if (label === undefined || label === '') label = window.location.href
  const value = Number(store.getters.transactionId)
  Vue.gtm.push({
    event: null,
    category: category,
    action: action,
    label: label,
    value: value
  })
}

I call this function from my components. I am using the 1.0.0 version here as other versions also show me the same error, and thought an earlier version would sometimes fix the issue.

Bug: last custom property is persisted

Info

When sending an event with custom parameters, the last parameters will be persisted to further calls if they are not overwritten. I'm not sure if this is intentional, but it's very annoying, since this makes other events send totally irrelevant data.
The dataLayer push is correct, but the actual values transmitted to GA4 are not.

Tool Version
Plugin v2
Vue v3.2.45

Input

  gtm.trackEvent({
    event: "test",
    event_parameter: "format",
    event_parameter_value: "test_value",
    user_property: "test_property",
    user_property_value: "test_prop_value"
  });
gtm.trackEvent({event: "test_followup"});

Output or Error

DataLayer - everything is correct here

dataLayer.push({
  event: "test",
  target: null,
  action: null,
  target-properties: null,
  value: null,
  interaction-type: false,
  event_parameter: "format",
  event_parameter_value: "test_value",
  user_property: "test_property",
  user_property_value: "test_prop_value",
  gtm.uniqueEventId: 1
})
dataLayer.push({
  event: "test2",
  target: null,
  action: null,
  target-properties: null,
  value: null,
  interaction-type: false,
  gtm.uniqueEventId: 2
})

gtag output - you can see the second test event also has the format property, eventhough it was not defined.

gtag("event", "test", {
  format: "test_value", // this is correct and as specified
  user_properties: {test_property: "test_prop_value"},
  send_to: "G-XXXX"
})

gtag("event", "test_2", {
  format: "test_value", // this should not be here!
  user_properties: {test_property: "test_prop_value"},
  send_to: "G-XXXXX"
})

Expected Output

gtag("event", "test", {
  format: "test_value",
  user_properties: {test_property: "test_prop_value"},
  send_to: "G-XXXX"
})

gtag("event", "test_2", {
  user_properties: {test_property: "test_prop_value"},
  send_to: "G-XXXXX"
})

Additional Context

If i send three events after each other, only the last custom parameter is persisted -> makes it seem even more like a bug 🤔
Since GA4 does not use action, category etc. anymore, the user has to specify their own parameter name and values.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.