我使用一个 nuxt 实例来为多个使用不同语言的域提供服务。对于每个域,我使用不同的 Google 跟踪代码管理器帐户。
在 nuxtServerInit 中,我将主机名和 Google 跟踪代码管理器 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 该解决方案的主要问题是所使用的模块本身。一个模块仅被调用一次,但它需要在每个请求时调用其他东西。
最佳答案
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
为整个文件禁用了 eslint。您只需为该行禁用它即可。
关于google-tag-manager - Nuxt服务器初始化 : Add Google-Tag-Manager scripts to head an body,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59253819/