GithubHelp home page GithubHelp logo

matteogabriele / vue-gtag Goto Github PK

View Code? Open in Web Editor NEW
857.0 8.0 63.0 1.38 MB

Global Site Tag plugin for Vue (gtag.js)

Home Page: https://matteo-gabriele.gitbook.io/vue-gtag/

License: MIT License

JavaScript 100.00%
vue-gtag vue analytics google-analytics gtags tracking

vue-gtag's Introduction


vue-gtag

Global Site Tag plugin for Vue

The global site tag (gtag.js) is a JavaScript tagging framework and API that allows you to send event data to Google Analytics, Google Ads, and Google Marketing Platform. For general gtag.js documentation, read the gtag.js developer guide.

Requirements

Vue ^3.0.0

Install

npm install vue-gtag

Documentation

Issues and features requests

Please drop an issue, if you find something that doesn't work, or a feature request at https://github.com/MatteoGabriele/vue-gtag/issues

Follow me on twitter @matteo_gabriele for updates

vue-gtag's People

Contributors

aetheon avatar based-ghost avatar cco3 avatar cesasol avatar davydevries avatar dependabot-preview[bot] avatar dependabot[bot] avatar drphil avatar gerrywilko avatar hugojeanmaire1 avatar kierans avatar matteogabriele avatar maucin avatar namoscato avatar raminjafary avatar samipe avatar stewartmckee avatar vladimyr avatar yihao-g 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  avatar  avatar  avatar  avatar  avatar  avatar

vue-gtag's Issues

How to include/use ecommerce?

I like to use vue-gtag in combination of the ecommerce plugin of google. Any idea how to load/include ga('require', 'ecommerce');

Events can still be the same I guess? Example ecommerce event:

ga('ecommerce:addTransaction', {
  'id': '1234',                     // Transaction ID. Required.
  'affiliation': 'Acme Clothing',   // Affiliation or store name.
  'revenue': '11.99',               // Grand Total.
  'shipping': '5',                  // Shipping.
  'tax': '1.29'                     // Tax.
});

EDIT: Nevermind after some digging I found: Purchase

Support anchor links for pageview tracking

In the old GA library when i just had the basic setup with

  Vue.use(
    VueGtag,
    {
      config: { id: "UA-XXXXX" }
    },
    router
  );

(of course the syntax looked a little bit different with the old library)

when i clicked a link /#test it was tracked as a pageview. In the new library it is not tracked anymore.

Can you enable that or tell me what needs to be done to support this?

Sample Code from the app is:
<v-btn to="/#test">test</v-btn>

V 1.0 Release Date?

Hey Matteo,

The company I work for is using vue-analytics and loving it, but we're wanting to migrate over to gtag for some of the newer features.

Do you have a status update on this library? We'd love to hear about any plans for the release of this project, or about any of the roadblocks that are still holding it back.

Thanks

Load new tag and initialize

needs to implement the current setup, programmatically.
copy code from vue-analytics

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=__domain_code__"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', '__domain_code__');
</script>

v1.6.0 broke typescript support in strict mode

Description

Trying to build a project that uses vue-gtag fails when type check and typescript strict mode is enabled.

Expected behavior

Build should work in strict mode.

Actual behavior

$ tsc --project ./tsconfig.json --noEmit
../../node_modules/vue-gtag/vue-gtag.d.ts:173:5 - error TS7010: 'config', which lacks return-type annotation, implicitly has an 'any' return type.

173     config(config?: GtagGenericParams);
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

../../node_modules/vue-gtag/vue-gtag.d.ts:174:5 - error TS7010: 'time', which lacks return-type annotation, implicitly has an 'any' return type.

174     time(timing: Timing);
        ~~~~~~~~~~~~~~~~~~~~~

../../node_modules/vue-gtag/vue-gtag.d.ts:208:30 - error TS7006: Parameter 'PluginOptions' implicitly has an 'any' type.

208   export function setOptions(PluginOptions): void;

Environment

vue-gtag 1.6.0
MacOS Catalina
TypeScript 3.7.5

Disable config request / inquiry.

Hello @MatteoGabriele,

Description

Maybe I missed this in the documentation, but is there a way to disable the plugin on development?

Expected behavior

I would like to pass to the config something like:
id: "XXXXX", params: { disable: true, // Set on ENV switch, for example. send_page_view: true }

This way I could just use the calls to this.$gtag everywhere in my app without extra checks.
Could this be a NICE TO HAVE contribution?

Thank you for the plugin, it is quite handy!

TypeScript type definitions

Thanks so much for creating this library, and its predecessor vue-analytics.

Do you have any plans to provide type definitions for vue-gtag? If not, and you're looking for someone to contribute this, would you prefer it to be maintained on DefinitelyTyped, or in this repo?

anonymize-ip: true, how does it work?

I am trying to send my requests to GA with 'anonymize_ip: true' but i can´t make it. I tried it within the options object and outside the options, with quotation marks and without...

I checked the Dev-Console networks tab for the 'collect?v...' request and would expected the "aip: 1' parameter in the query string parameters...

What am i doing wrong?

my code:

import Vue from "vue";
import VueGtag from "vue-gtag";
import router from "./../router";

Vue.use(
VueGtag,
{ config: { id: "UA-example-0" }, bootstrap: false },
router
);

i activate GA after checking the cookie with the bootstrap function.

How to opt out after opt in

Hi!

at first, thanks for your work on this plugin.

I've implemented vue-gtag with the boostraping strategy. GDPR also requires that users can opt out afterwords. So far I've implemented and optOut method to disable tracking, but can still see page tracking via GTM/GA Debug Chrome Plugin.

Is this the correct way to go for?

optOut() {
      setOptions({
        enabled: false,
      });

      this.SET_COOKIE_CONSENT_LAYER_DECLINED();
      bootstrap();
    },

Furthermore, is there a way where I can get the current configure options of vue-gtag within a component, e.g. to check if its enabled?

Thanks in advance and happy new year!

Carl

Send events from Vuex

Hi @MatteoGabriele - firstly thank you for a fabulous plugin (also thank you for vue analytics)

This is just a quick query if I may.

Is it possible to send events or exceptions in my case from a Vuex module

I have a Vuex module in a file called auth.js and would like to send an exception to GA if an error happens in there, something along the lines of:

import { exception } from 'vue-gtag'

auth.checkSession((err, result) => {
  if (err) {
    exception({
      'description': err,
      'fatal': false
    })
  } else {
    // . . . carry on 
  }
})

I can't seem to get to work though am I doing something wrong or hasn't this been implemented (I haven't seen it in the docs so I'm guessing the latter) - if not implemented is there a way I can get to work?

send Timing after route changed

Description

Can i send timings after set pageview (route change)

Expected behavior

Sending timings after set pageview(route change) from configs

Actual behavior

doesn't sending timing info when routing changed

Boostrap later doesn't work

If you are reporting a bug, please fill in below. Otherwise feel free to remove this template entirely.

Description

What are you reporting?
Boostrap later doesnt work

In main.js
import Vue from "./vue";
import store from "./FormStore.js";
import VueRouter from "vue-router";
import VueGtag from "vue-gtag";
Vue.use(VueGtag, {
config: { id: "UA-xxxxxxxx-y" },
router,
bootstrap: false
});

In app.vue
import { setOptions, bootstrap } from 'vue-gtag';

mounted() {
bootstrap(gtag).then(() => {
console.log("Gtag Actif ? ", gtag);
});
}

get htis message in console

Vue warn]: Error in mounted hook: "ReferenceError: gtag is not defined"

found in

---> at src\components\App.vue

Expected behavior

Gtag should be defined
Tell us what you think should happen.

Actual behavior

Vue warn]: Error in mounted hook: "ReferenceError: gtag is not defined"
Tell us what actually happens.

Environment

Vue 2.0, windows 10 64 bits, Chrome browser ( idem with Mozilla)
Run this command in the project folder and fill in their results:

npm ls vue-gtag:
`-- [email protected]
Then, specify:

  1. Operating system:
    windows 10 64 bits,
  2. Browser and version:
    Chrome browser ( idem with Mozilla)

Reproducible Demo

I folowed documentation :
import { bootstrap } from 'vue-gtag'

export default {
name: 'MyComponent',

methods: {
enablePlugin () {
bootstrap(gtag).then(() => {
// all done!
})
}
}
}
the bootstrap method will return a promise that will be resolved when the script has been loaded completely.
Please take the time to create a new app that reproduces the issue or at least some code example
In main.js
import Vue from "./vue";
import store from "./FormStore.js";
import VueRouter from "vue-router";
import VueGtag from "vue-gtag";
Vue.use(VueGtag, {
config: { id: "UA-xxxxxxxx-y" },
router,
bootstrap: false
});

In app.vue
import { setOptions, bootstrap } from 'vue-gtag';

mounted() {
bootstrap(gtag).then(() => {
console.log("Gtag Actif ? ", gtag);
});
}
Demonstrable issues gets fixed faster.

Thank You in advance for your help

SPA Auto Tracking not working

If you are reporting a bug, please fill in below. Otherwise feel free to remove this template entirely.

Description

The auto-tracking of VueRouter pages seems to not be working, I'm currently viewing my /articles router but Google Analytics only displays / as the current active route. See code on Demo section

Expected behavior

Google Analytics should track VueRouter's routes for SPAs

Actual behavior

Nothing happens, only tracks / which is the index page

Environment

Run this command in the project folder and fill in their results:

npm ls vue-gtag:

Then, specify:

  1. Operating system: macOS Catalina
  2. Browser and version: Chrome 80.0.3987.122

Reproducible Demo

I'm using the vue-cli for this with a separate main.js(entry point) and router.js files.

router/index.js (this is the router.js file)

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/pages/Home'
import About from '@/pages/About'
import Articles from '@/pages/Articles'
import VueGtag from 'vue-gtag'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
  },

  {
    path: '/about',
    name: 'About',
    component: About,
  },

  {
    path: '/articles',
    name: 'Articles',
    component: Articles,
  }
]

Vue.use(VueGtag, {
  config: { id: 'UA-159900000-1' }
}, router)

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

main.js

import Vue from 'vue'
import App from '@/App'
import router from '@/router'
import axios from 'axios'
import '@/assets/tailwind.css'

Vue.config.productionTip = false

Vue.prototype.$http = Vue.$http = axios

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

api documentation

I just gave a sad face to "Was this page helpful" at https://matteo-gabriele.gitbook.io/vue-gtag/methods/events and wanted to provide feedback why.

I was expecting this to have the full API documentation for the method, ie. what exact parameters can I pass.

Coming from native gtag the method is gtag('event', 'action', { 'event_category', category, 'event_label', label, 'value', value }) how to do this with $gtag is unclear.

Question: Custom Fields

I had previously used your vue-analytics library, and I saw that you recommended vue-gtag going forward.

We have a custom field for userId in our Google Analytics. Below was the usage to tell vue-analytics about it.

In this case, looking to accomplish the same thing with vue-gtag - to pass in the userID field from my app into the vue-gtag library.

Thanks!

Vue.use(VueAnalytics, {
id: "GAID",
fields: {
userId: "user123",
},
set: [

  { field: 'user_id', value: "user123" },

],
router,

debug: {
enabled: false, // default value
trace: false, // default value
sendHitTask: true, // default value
},
});

just test for issue

If you are reporting a bug, please fill in below. Otherwise feel free to remove this template entirely.

Description

What are you reporting?

Expected behavior

Tell us what you think should happen.

Actual behavior

Tell us what actually happens.

Environment

Run this command in the project folder and fill in their results:

npm ls vue-gtag:

Then, specify:

  1. Operating system:
  2. Browser and version:

Reproducible Demo

Please take the time to create a new app that reproduces the issue or at least some code example

Demonstrable issues gets fixed faster.

Not working when using `vue-cli-service build`

Description

The plugin is not working when building a vue.js app using vue-cli-service build. There is an error displayed in console without much informations saying why it's not loading :

image

Expected behavior

It should load or at least display why it's not loading.

Actual behavior

Tell us what actually happens.

Environment

I run vue-cli-service build then upload on a feature phone (KaiOS) that embed web content in iframes as application (Firefox OS).

share knowledge!

Since this Google gtag.js project is pretty new and kinda complicated, with not so much documentation yet and very less amount of actual implementation example into real project, whatever you know that you want to share or if you want to contribute with your code: please feel free to do :)

cheers!

Checking if gtag has been initialized

I am using bootstrap to set gtag after receiving the GA tracking id via an API.

There are times where there is no GA tracking id, so the gtag does not get initialized.

I would like to check if gtag has been configured before calling a tracking method (otherwise I get an error).

I have been trying to load the getOptions() method, but haven't been able to make it work.

What would be the best way to check if gtag has been initialized?

How to enable after user consent?

Matteo, first of all thanks a lot for this awesome plugin!

I'm building a cookie banner and as per the documentation I can see how I can load the plugin with enabled: false. What is missing from the docs is how to actually enable it again after user consent - including sending the first pageview.

Can you point me into the right direction?

Thanks in advance - all the best,
Sumit

Something happened and gtag.js couldn't be loaded

Description

"gtag.js couldn't be loaded"

image

Expected behavior

Is should load the gtag.js library.

Actual behavior

"gtag.js couldn't be loaded"

Environment

Using vue-gtag version 1.1.2.

  1. Operating system: Mac OS 10.15.2 (19C57)
  2. Browser and version: Google Chrome 79.0.3945.130

Reproducible Demo

Created empty vue project with vue create, added vue-gtag by using yarn add vue-gtag

main.ts

Vue.use(VueGtag, {
  config: { id: 'GTM-XXXXXX' },
});

Use with Gridsome

This is really a request for a bit of guidance on using vue-gtag with Gridsome. I can just about get something going as far as basic analytics tagging but I'm trying to figure out a conversion event for a specific page and I'm stuck.

I know you can import VueGtag in the main.js and add the ID there too... but the closest I've got in the individual page script is the following, which doesn't quite work:

this.$gtag.event('conversion', {
             'send_to': 'AW-000000/randomlettersetc',
           });

Any thoughts? I know this is probably very easy but I'm getting to grips with both Vue and Gridsome at the same time and docs aren't always clear about how to translate from the general to the specific.

Add tracking ID dynamically

If you are reporting a bug, please fill in below. Otherwise feel free to remove this template entirely.

Description

What are you reporting?

Expected behavior

Tell us what you think should happen.

Actual behavior

Tell us what actually happens.

Environment

Run this command in the project folder and fill in their results:

npm ls vue-gtag:

Then, specify:

  1. Operating system:
  2. Browser and version:

Reproducible Demo

Please take the time to create a new app that reproduces the issue or at least some code example

Demonstrable issues gets fixed faster.

Possible to wait until user consent is checked, and then track view?

I have a script that runs on mounted() and checks with an axios response that the user has agreed to google analytics. This means that on each page load, an axios call is made which, if returned true (permission from user to use google analytics) we then call:

launchGoogleAnalytics(){ Vue.use(VueGtag, { config: { id: "my-id" }, enabled: true }); },

Would this also track the current page view/session, or not? VueGtag is not loaded until after we confirm user consent, so I'm thinking maybe the page view won't be tracked?

Opt-out for multiple domain tracking not working

Description

Hello,
I'm trying to combine the use of multiple domain tracking, bootstrap and opt out but it doesn't seems to be working.

Expected behavior

I would like for my user to be able to opt-in and opt-out simply by clicking on a button to activate it or not.

Actual behavior

When I'm calling this.$gtag.optOut(), it stops triggering the main id (UA-XXXXXXXX-1) but the id specified in includes (UA-XXXXXXXX-2) is still used to trigger events to Google Analytics.

Here is my code in main.ts:

Vue.use(VueGtag, {
  config: { id: "UA-XXXXXXXX-1" },
  includes: [
    { id: "UA-XXXXXXXX-2" }
  ],
  bootstrap: false,
  enabled: false
}, router);

And when I'm using it:

bootstrap().then(() => {
  analyticalCookie.IsAccepted ? this.$gtag.optIn() : this.$gtag.optOut();
});

Maybe I misinterpreted something in the documentation and it works as supposed to.

Thanks in advance, I can give more details if needed :)

Misleading error when using pageTrackerScreenviewEnabled with pageTrackerTemplate

I was wrestling with this error for a bit:
To use the screenview, add the appName to the plugin options
with this configuration:

    Vue.use(VueGtag, {
      config: {
        id: options.gTag,
        params: {
          language: i18n.locale
        }
      },
      pageTrackerScreenviewEnabled: true,
      appName: "Participant Portal",
      pageTrackerTemplate(to) {
        return {
          screen_name: to.name,
          user_id: store.getters.getParticipant ? store.getters.getParticipant.id : null,
        }
      }
    }, router);

After digging into the source code it became apparent, that the top level option of appView only gets set in the template if you're not using a custom one, otherwise you need to set app_view within your pageTrackerTemplate method. Would it make sense to report a different error if they have a custom pageTrackerTemplate that's missing app_view?

user_properties in gtag

Thanks so much Matteo! gtag is amazing, but I'm being blocked by a big thing:

How do I set user properties for a user, like the identify call in Segment, or https://developers.google.com/analytics/devguides/collection/app-web/user-properties for gtag?

In gtag, I can dynamically set user properties as follows:

gtag('set', 'user_properties', {
  favorite_composer: 'Mahler',
  favorite_instrument: 'double bass',
  season_ticketholder: 'true'
});

How would I do this with vue-gtag? I've already looked into this.$gtag.set but it doesn't seem to apply.

Tracking page views (dl, dh and dp query parameters)

Description

Hi! Thanks for vue-analytics and vue-gtag! I've noticed an unexpected behaviour when trying out vue-gtag.

Expected behavior

Say we have two URLs: example.org/about and example.org/contacts. When I go from /about to /contacts, I expect collect request to have dl=example.org/contact or dh=example.org&dp=/contact.

Actual behavior

What I see is dl=example.org/about&dp=/contacts. Is this intended behaviour? As far as I understand, there should be either only dl or both dh and dp, where dl is the location of the current document (example.org/contacts), dh is hostname and dp is the path.

https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#dl

Reproducible Demo

https://codesandbox.io/s/zen-gauss-9szcy

Screenshot 2020-01-20 at 18 05 17

If what I see is indeed unintended, maybe the problem is here:

page_location: window.location.href

window.location.href should be replaced with window.location.host

Google Ads: Conversion event

Description

I want to emit an Google Ads conversion event. Google generated the following code:

gtag('event', 'conversion', {
    'send_to': 'AW-424270545/dwgaH7KkocA6EJHh7MAC',
    'event_callback': callback
});

How does that translate to

this.$gtag.event(<action>, {
        'event_category': <category>,
        'event_label': <label>,
        'value': <value>
      })

I already initialized gtag with my global (Google Ads) gtag.

Thanks in advance!

Disable auto tracking on certain component ? Set page title from vue-meta title ?

This is a question / feature request

I didn't see in the docs if it was possible to disable auto-tracking on specific components.
Use Case : Certain pages can have a title from remote data, so pageView would be sent after the component is loaded and therefore way after router.afterEach.

Also, is there an intergration with vue-meta in the pipe as it's the most used plugin for meta data?
Use case: Getting the title from the component's meta info function.

export default {
  metaInfo() {
    return { title: `title part ${this.endTitle}` }
  },
  data() {
    return { endTitle: 'title part 2'}
  }
}

Question 1 could resolve Question 2 in a cheap manner as I would send manual pageViews when I need it based on reactive data.

use gtag inside onReady

Hi, I need to set gtag adwords' config.
I'm using onReady option with global gtag:

onReady() {
  if (typeof gtag === 'function') gtag('config', 'AW-796275892')
}

There's another way?

How to Use functions or/and Promises when initializing VueGtag config.id

I am looking for a way to initialize VueGtag with the response of an API call.

I have tried setting it with a function/promise as the vue-analytics plugin but it is not working...
https://github.com/MatteoGabriele/vue-analytics/blob/master/docs/installation.md#use-functions-orand-promises

The solution that seems to be working is to initialize the VueGtag after the API response

  axios.get('api_endpoint').then(response => {
    const gtag_id = response.data
    Vue.use(VueGtag, {
      config: {
        id: gtag_id
      }
    })
  })

I am not sure this is the best way. Do you have any other suggestions?

Thank you

NUXT Module Available?

I am starting a new NUXT application and have a requirement to add google analytics. There is currently an analytics-module package in the nuxt-community that utilizes your vue-analytics package, but I have not been able to find one for your new vue-tag package. Do you know if one exists?

Send event - set category, label, etc

In the documentation for tracking events there's this code:

this.$gtag.event('login', { method: 'Google' })

but no information on how to set the event category, label, etc.
With the code above, the event shows in our analytics with category general, action login and nothing else.
I'm missing something, but haven't figured out what.
Thanks.

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.