nuxt-community / legacy-modules

MIT License
1.29k stars 157 forks source link

google-analytics - custom variables #46

Open awronski opened 7 years ago

awronski commented 7 years ago

Hi!

How can I pass custom variables to GA?

I need to set custom variables for selected pages, eg:

  ga('set', 'expId', 'xxxx');     
  ga('set', 'expVar', '1'); 

It has to be done before ga('send', 'pageview');

Any suggestions? :)

This feature request is available on Nuxt.js community (#c22)
awronski commented 7 years ago

@pi0 do you have any suggestion how to implement it? Maybe I could do it and share.

pi0 commented 7 years ago

Hi @awronski . That would be nice if you are interested. I think we can access to route meta data for additional fields like analytics so page components can use analytics: { expId: 123 } to set that meta, then here we can conditionally check that field existance and setting all of them using ga('set'). Here is an example how nuxt accesses pages transition property.

awronski commented 7 years ago

@pi0 I have this change almost working :)

The problem is that the router.afterEach((to, from) don't see to.meta.analytics for the first request.

For the following requests it is working ok. I set the meta in the middleware like this:

export default function ({ route, store }) {
  route.meta.analytics = {
    expId: 12345,
    expVar: Math.floor(Math.random() * 3) + 1
  }
}

How can I change it to work with the initialization too?

pi0 commented 7 years ago

@awronski We can access to first page on plugin load using router. So maybe we can refactor function inside afterEach and call it once again on plugin load. PS: Waiting for PR :D