如何使用 react-ga 在 ReactJS 中注册到 Google Adwords 的转换?

Posted

技术标签:

【中文标题】如何使用 react-ga 在 ReactJS 中注册到 Google Adwords 的转换?【英文标题】:How to register conversion to Google Adwords in ReactJS with react-ga? 【发布时间】:2020-10-29 20:56:23 【问题描述】:

我正在使用 react-ga,效果很好。我可以调用事件并跟踪页面。

但 Google Adwords 中的转换脚本有点不同:

<script>
function gtag_report_conversion(url) 
  var callback = function () 
    if (typeof(url) != 'undefined') 
      window.location = url;
    
  ;
  gtag('event', 'conversion', 
      'send_to': 'AW-XXXX/XXXX',
      'value': 140.0,
      'currency': 'BRL',
      'transaction_id': '',
      'event_callback': callback
  );
  return false;

</script>

使用 React-GA,我可以像这样注册事件:

ReactGA.event(
      category: "User",
      action: "Click Whatsapp button",
      value: 1,
    );

问题是对象没有属性“send_to”、“event_callback”、“currency”、“transaction_id”。

所以我必须使用 ga 对象来执行此操作(我认为)。我不知道 Google Adwords 告诉我使用的 ga 对象和 gtag 对象之间是否有区别。

我尝试注册转换但没有任何反应:

 ReactGA.ga("event", "conversion", 
      send_to: "AW-XXXX/XXXX",
      value:  140.0,
      currency: "BRL",
      transaction_id: "",
 );

【问题讨论】:

【参考方案1】:

在尝试了许多不同的方法之后,这才是真正解决这个问题的方法:

在 public/index.html 中添加标签而不调用配置:

    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXX"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag() 
        dataLayer.push(arguments);
      
      gtag('js', new Date());
    </script>

然后将此路由添加到所有路由之上和 Switch 组件之外:

       // This will be called every time the location change
       <Route
          path="/"
          render=( location ) => 
            window.gtag('config', 'UA-XXXXXXXXX', 
              page_path: location.pathname + location.search,
            );
          
        />

现在您可以在任何地方使用带有所有参数的 gtag 对象:

    window.gtag('event', 'purchase', 
      send_to: 'AW-XXXX/XXXX',
      value: order.orderTotal,
      currency: 'BRL',
      transaction_id: order.orderId,
      shipping: parseFloat(order.shipping.price),
      items: formatedItems,
    );.

【讨论】:

以上是关于如何使用 react-ga 在 ReactJS 中注册到 Google Adwords 的转换?的主要内容,如果未能解决你的问题,请参考以下文章

在 Flux 架构中,您如何管理分析跟踪?

如何在 Wordpress 插件中使用 ReactJS

如何在骨干和angularjs中使用reactJS组件

如何在两个不同的组件中使用路由 - ReactJS

如何在ReactJS中使用JQuery

如何在 reactJS 中使用 Thymeleaf th:text