12
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

NuxtにGTMを入れて、ページタイトルをGAに送る

Last updated at Posted at 2019-05-28

Nuxtに@nuxtjs/google-tag-managerをインストールしても、GA上でページタイトルが取得するために少し工夫がいるため、@nuxtjs/google-tag-managerを使用しないでGTMからGAに送るようにしました。
(GTMの設定は割愛します)

gtm.js
class GTM {
  constructor(ctx, id) {
    this.ctx = ctx
    this.id = id
    this.loadScript(id)
  }

  loadScript(id) {
    const win = window, doc = document, script = doc.createElement('script'), dl = 'dataLayer'
    win[dl] = win[dl] || []
    win[dl].push({
      event: 'gtm.js',
      'gtm.start': new Date().getTime(),
    })
  
    if (!id) {
      return
    }
    script.async = true
    script.src = `https://www.googletagmanager.com/gtm.js?id=${id}`
    doc.body.appendChild(script)
  }

  pageTracking() {
    this.ctx.app.router.afterEach(function(to) {
      setTimeout(() => {
        window['dataLayer'].push({
          event: 'NuxtRoute',
          pageType: 'PageView',
          pageUrl: to.fullPath,
          routeName: document.title
        })
      }, 500)
      // ページ遷移時に、遷移前のタイトルを送ることがあるのでsetTimeoutで少し遅らせる
    })
  }
}

export default (ctx, inject) => {
  // 本番環境以外は動かさない
  if(process.env.NODE_ENV != 'production') return
  const $gtm = new GTM(ctx, 'GTM-XXXXXXX')
  // 今後の拡張のためinjectして、すべてのコンポーネントで使えるようにする
  inject('gtm', $gtm)
  $gtm.pageTracking()
}
nuxt.config.js
  plugins:[
    { src: '@/plugins/gtm.js', ssr: false }
  ]

結構無理やりな実装になってしまいました。。。。

12
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?