gtm

GoogleGTM

GoogleGTM

920 发布: 2024/12/1 10:00 本文总阅读量

Nuxt2中添加Google-GTM

示例

<!-- 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-TKSGKJXR');</script>
<!-- End Google Tag Manager -->

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

开工

1.创建analytics.js

  • 放置路径根目录/static/js/analytics.js
//
(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-TKSGKJXR');

window.dataLayer = window.dataLayer || [];

function gtag() {
    dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', 'G-TKSGKJXR');

2.nuxt.config.js

  • head节点的script里添加如下代码:注意analytics.js
script: [
    // Google Analytics Code
    {
        src: "https://www.googletagmanager.com/gtag/js?id=GTM-TKSGKJXR",
        async: true,
    },
    // Import analitics.js file
    {
        src: "/pc/js/analytics.js"
    },
],

3.body-noscript

  • 放置位置根目录/layouts/default.vue
mounted() {
    /*
    let noscriptDom = document.createElement('noscript')
    noscriptDom.innerHTML = `<iframe
        src="https://www.googletagmanager.com/ns.html?id=GTM-TKSGKJXR"
        height="0"
        width="0"
        style="display:none;visibility:hidden">
        </iframe>`
    document.body.insertBefore(noscriptDom, document.getElementById('__nuxt'))
    */
   let noscriptDom = document.createElement('noscript');
   let iframe = document.createElement('iframe');
   iframe.src = 'https://www.googletagmanager.com/ns.html?id=GTM-TKSGKJXR';
   iframe.height = '0';
   iframe.width = '0';
   iframe.style.display = 'none';
   iframe.style.visibility = 'hidden';
   noscriptDom.appendChild(iframe);
   document.body.insertBefore(noscriptDom, document.getElementById('__nuxt'));
}

效果

示例 示例

检测

示例

参考1
参考2
参考3-nuxt3?未验证