gtm-support / vue-gtm Goto Github PK
View Code? Open in Web Editor NEWSimple implementation of Google Tag Manager for Vue
Home Page: https://www.npmjs.com/package/@gtm-support/vue-gtm
License: MIT License
Simple implementation of Google Tag Manager for Vue
Home Page: https://www.npmjs.com/package/@gtm-support/vue-gtm
License: MIT License
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.
More here: https://groups.google.com/a/chromium.org/g/chromium-extensions/c/0mPEDNJA0XM?pli=1
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!
...
...
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
.
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.
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
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 |
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"});
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"
})
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"
})
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.
Is it possible to add countent_group
to the request? So foe example I can add different groups per page.
thank you
...
...
Tool | Version |
---|---|
Plugin | v2 |
Vue | v2.6.12 |
Node | v14 |
OS | mac |
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)
},
};
GTM tag is not firing the website
I am expecting GTM to fire the website.
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.?
Tool | Version |
---|---|
Plugin | v1.6.0 |
Vue | v4.0.12 |
Vue-Router | v3.2.31 |
Node | v16.15.0 |
OS | win(WSL) |
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
})
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'.
no type error
Tool | Version |
---|---|
Plugin | v1.2.2 |
Vue | 3.2.20 |
Node | v17.0.1 |
OS | mac |
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.
Tool | Version |
---|---|
Plugin | v2.2.0 |
Vue | v3.0.0 |
Node | v18.7.1 |
OS | mac |
app.use(
createGtm({
id: 'GTM-xxxxxx',
vueRouter: router
Property 'vouRouter' doesn't exist.
// nothing
The README states how to pass the router
to the plugin. However, the mentioned property doesn't exists.
How to do that?
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!
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.
Tool | Version |
---|---|
Plugin | v2.0.0 |
Vue | v3.2.47 |
Node | v16.19.0 |
OS | mac |
createGtm({
id: 'GTM-XXXXXXX',
enabled: true,
loadScript: true,
vueRouter: router,
nonce: '2726c7f26c',
})
Nonce is not output into Script tag
nonce should be added to script tag created by the package
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
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 ?
Tool | Version |
---|---|
Plugin | v2.0.0 |
Vue | v3.2.0 |
Node | v18 |
OS | mac |
npm install
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
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.
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.
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 | 2.2.0 |
Vue | v3 |
Node | v16.17.1 |
OS | linux,mac |
createGtm({
id: "G-XXXXXXXXXX", // Gtm 4 ID
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`
enabled: true, // 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: useRouter(), // Pass the router instance to automatically sync with router (optional)
//ignoredViews: ['homepage'], // Don't trigger events for specified router names (optional)
trackOnNextTick: true, // Whether or not call trackView in Vue.nextTick
})
'G-XXXXXXXXXX' is not a valid GTM-ID (/^GTM-[0-9A-Z]+$/).
I would expect a console warning Your are using an invalid GTM ID and the app should load but without GTM.
To add support for GTM 4 ID format that starts with G- instead of GTM-
Tool | Version |
---|---|
Plugin | v2.0.0 |
'G-xxxxxxxxxx' is not a valid GTM-ID (/^GTM-[0-9A-Z]+$/). Did you mean 'GTM-xxxxxxxxxx'?
bug with install npm 7 without --legacy-peer-deps
peer vue@"^3.0.0" from @gtm-support/[email protected]
for vue 3.1.0-beta.3
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()
}
}
})`
Tool | Version |
---|---|
Plugin | v1.3.0 |
Vue | v2.7 |
Node | v16.10.0 |
OS | win |
I am using your plugin like this:
I am using this information I got from Google Analytics:
The measurement ID I am using as an ID is: G-G1HQXCMMVY
I am getting an error with the page and it doesn't load anything:
What is the right ID to use to make the plugin works?
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.
Is Google Analytics 4 supported yet? Any plans to do that? The old support runs out 1. Juli 2023
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
Environment variable
VUE_APP_GTM_ID=G-XXXXXXXXX
Vue.use(VueGtm, {
id: process.env.VUE_APP_GTM_ID,
vueRouter: router
});
Uncaught Error: 'G-XXXXXXXXX' is not a valid GTM-ID (/^GTM-[0-9A-Z]+$/). Did you mean 'GTM-XXXXXXXXX'?
Tool | Version |
---|---|
Plugin | v1.3.0 |
Vue | v2.7.10 |
Node | v18.9.0 |
OS | win |
"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"
}
}
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.
Do I need to replace the gtm_auth: 'AB7cDEf3GHIjkl-MnOP8qr'?
If so, where do I get this?
Tool | Version |
---|---|
Plugin | v2.2.0 |
Vue | v3.0.0 |
Node | v18.7.1 |
OS | mac |
app.use(
createGtm({
id: 'GTM-xxxxxx',
vueRouter: router
Property 'vouRouter' doesn't exist.
// nothing
The README states how to pass the router
to the plugin. However, the mentioned property doesn't exists.
How to do that?
Tool | Version |
---|---|
Plugin | ^2.0.0 |
Vue | v2.x.x |
Node | 14.17.0 |
OS | win |
const baseUrl = vueRouter.options.base ?? ""
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
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
I'm using @gtm-support/vue-gtm
in Nuxt 3 App
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?
Tool | Version |
---|---|
Vue | v3.2.37 |
vue-router | v4.1.1 |
vue-gtm | v1.6.0 |
OS | mac |
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");
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
Moved frm vue2 to vue3. tried "@gtm-support/vue-gtm": "^1.6.0", but get this error
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 |
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");
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
I would expect a console warning Your are using an invalid GTM ID
and the app should load but without GTM.
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)
}
I found that the event name is' Content-view 'and cannot be customized, would you consider supporting incoming?
Tool | Version |
---|---|
Plugin | v2.0.0 |
Vue | v3.2.45 |
Node | v18.12.1 |
OS | mac |
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,
}),
);
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
Should work as expected.
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.
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?
Tool | Version |
---|---|
Plugin | v1.6.0 |
Vue | v3.2.13 |
Vite | v2.9.13 |
Node | v8.13.2 |
OS | mac |
// 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");
โ [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
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.
Line 119 in 299e878
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.
Tool | Version |
---|---|
Plugin | v2.2.0 |
Vue | v3.3.4 |
Node | v18.3.0 |
OS | win |
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')
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'?
Working application and plugin
Inject the needed scripts (in the head and body tag) in SSR, so the server wil render the tags.
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!
Hello everyone
Is there a way to track a custom event and pass a category and label without those two values being passed as target and target-properties?
Tool | Version |
---|---|
Plugin | v2.1.0 |
Vue | v3.3.4 |
Node | v18.17.1 |
OS | win |
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.
I expect no unexpected pushes.
We are running this with nuxt3.
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.
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?
Tool | Version |
---|---|
vue-gtm | v1.6.0 |
Vue | v3.2.37 |
OS | linux |
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);
},
});
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
I just installed it on Vue3 I don't have vue-router and I'm not going to use it.
I see that @gtm-support/core
hav option to set source
for server side gtm script but @gtm-support/vue2-gtm
doesn't allow to set source
option
...
tried
Vue.use(VueGtm, { source: "https://insight.blabla.com/gtm.js", id: "123", });
but it still load script from @default https://www.googletagmanager.com/gtm.js
...
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?
Adding a new property to tell the set up to use partytown.
https://partytown.builder.io
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';
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.