【问题标题】:How to get google analytics to show correct active page on SPA using gtag.js?如何让谷歌分析使用 gtag.js 在 SPA 上显示正确的活动页面?
【发布时间】:2018-04-09 17:13:58
【问题描述】:

我是 Google Analytics(分析)的新手,所以我继续将gtag.js 代码添加到我的 HTML 页面标题中,它非常适合初始页面加载。但是,我使用 React 和 react-router 来动态更改 URL,当我的 SPA 中发生 URL 更改时,Google Analytics 不会获取活动页面中的更改或新点击。

我找到的答案是ga.js,而不是gtag.js。我尝试在其他答案中使用 URL 侦听器调整 Google's documentation suggestion here 以满足我的需要。但尽管代码在动态页面加载时运行,但没有任何内容发送到 GA。

window.gtag && history.listen((location)=>{
    console.log('>>>', location.pathname)
    gtag('config', 'GA_TRACKING_ID', {'page_path': location.pathname});
    // window.ga('set', 'page', location.pathname);  //--> this would have worked with ga.js
    // window.ga('send', 'pageview', location.pathname);
});

【问题讨论】:

    标签: javascript google-analytics google-tag-manager


    【解决方案1】:

    我想这可能是一个 React 问题。考虑检查这个线程: React router 4 history.listen never fires

    【讨论】:

    • 我真的想通了。我会发布答案。 history.listen 触发了它是 GA 没有触发,但事实证明解决方案很简单并且在代码之外处理(来自 GTM)。
    • 啊,你没有提到你正在用 GTM 解雇这些东西。我想你不需要gtag('config', 'GA_TRACKING_ID', {'page_path':location.pathname}); 那么dataLayer.push() 就足以触发标签了。
    • BTW GTM 内置了历史更改监听器,因此您不必从代码中创建 dataLayer.push
    • 有趣,你有没有关于这个的链接供参考?
    【解决方案2】:

    解决方案原来是在 Google 跟踪代码管理器方面。如果 GTM 端没有侦听此事件的触发器和侦听该触发器的标记,则触发我链接的 GTM 文档中显示的事件将没有任何好处。

    所以步骤是:

    1. 将应用连接到 Google 跟踪代码管理器
    2. 在 Google 跟踪代码管理器中创建一个触发器以监听 VirtualPageview 事件
    3. 创建一个监听第 2 步中创建的触发器的标签,这个标签是一个谷歌分析标签
    4. 现在只需让代码触发VirtualPageview 事件即可。如下图所示完成

    --

    export function virtualPageviewOnRouteChange(history){
        let previousPathname = null
        window.gtag && history.listen((location)=>{
            if(previousPathname != location.pathname){
                previousPathname = location.pathname;
                gtag('config', 'GA_TRACKING_ID', {'page_path':location.pathname});
                dataLayer.push({
                    'event':'VirtualPageview',
                    'virtualPageURL':location.pathname,
                });
            }
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-11
      • 1970-01-01
      • 2020-12-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多