NuxtServerInit:添加Google-Tag-Manager脚本来引导正文

时间:2019-12-09 17:27:33

标签: google-tag-manager nuxt.js

我使用一个nuxt实例来服务具有不同域的多个域。对于每个域,我使用一个不同的Google Tag Manager帐户。

在nuxtServerInit中,我将主机名以及Google-Tag-Manager ID添加到商店中。

现在,我正在寻找一种将JavaScript代码段添加到我的nuxt项目中的方法。

这个应该在脑子里

<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXX);</script>
<!-- End Google Tag Manager -->

那是身体的开始

<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->

我的第一个想法是将这些代码以编程方式添加到文档中,但是我不知道如何。

有什么建议或更好的主意吗?

我已经尝试使用社区解决方案。但是它不支持不同的ID。 Can anyone help implementing Nuxt.js Google Tag Manager with function based id 该解决方案的主要问题是本身使用的模块。一个模块仅被调用一次,但在每次请求时都需要调用其他模块。

1 个答案:

答案 0 :(得分:2)

This question很相似,并帮助我找到了答案。

plugins/gtm.js(或您要命名的任何名称)上创建一个新插件:

// plugins/gtm.js

let gtmKey;

// In this example I care about the page title but you can use other properties if you'd like
switch(document.title) {
  case 'Title 1':
    gtmKey = 'GTM-XXXXXX1';
    break;
  case 'Title 2':
    gtmKey = 'GTM-XXXXXX2';
    break;
  default:
    break;
}

export default () => {
  if (!gtmKey) { // In case I have other pages not in the switch statement above
    return;
  }
  /*
  ** Include Google Tag Manager
  */
  (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
    new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
    j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
    'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
  })(window,document,'script','dataLayer', gtmKey);
}

然后从nuxt.config.js加载:

// nuxt.config.js
export default {
  ...
  plugins: [{ src: '~/plugins/gtm.js', mode: 'client' }],
  ...
}

注释1:我真的不喜欢将标题硬编码到此插件中的方式,因为在我的其中一个页面上标题的更新可能会在我不知情的情况下破坏它。欢迎在这里提出建议。

注意2:我的eslint抱怨在GTM核心关闭之前(就在(function...之前没有分号),因此我实际上只是用// eslint-disable。您可以仅将其禁用。