如何使用 gtag.js 获取 google 分析以在 SPA 上显示正确的活动页面?

How to get google analytics to show correct active page on SPA using gtag.js?

我是 Google Analytics 的新手,所以我继续将 gtag.js 代码添加到我的 HTML 页面 header,它非常适合初始页面加载。但是,我使用 React 和 react-router 来动态更改 URL 和 Google 当我的 SPA 发生 URL 更改时,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);
});

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

解决方案原来是在 Google 跟踪代码管理器方面。如果 GTM 端没有监听此事件的触发器,并且没有监听该触发器的标签,那么按照我链接的 GTM 文档中所示触发事件不会有任何好处。

所以步骤是:

  1. 将应用连接到 Google 跟踪代码管理器
  2. 在 Google 跟踪 VirtualPageview 事件的跟踪代码管理器中创建触发器
  3. 创建一个标签来监听在第 2 步中创建的触发器,这个标签是一个 Google Analytics 标签
  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,
            });
        }
    });
}