【问题标题】:GTM, Object Description Error? Only supported for ECMASCRIPT6 mode?GTM,对象描述错误?仅支持 ECMASCRIPT6 模式?
【发布时间】:2021-04-19 21:39:35
【问题描述】:

我正在尝试使用 GTM 将数据从 webVitals 发送到谷歌分析。

使用这个包:https://github.com/GoogleChrome/web-vitals#load-web-vitals-from-a-cdn

<script defer src="https://unpkg.com/web-vitals@1.1.0/dist/web-vitals.umd.js"></script>
<script>
function sendToGoogleAnalytics ({name, delta, id}) {
  // Assumes the global `gtag()` function exists, see:
  // https://developers.google.com/analytics/devguides/collection/gtagjs
  gtag('event', name, {
    event_category: 'Web Vitals',
    // The `id` value will be unique to the current page load. When sending
    // multiple values from the same page (e.g. for CLS), Google Analytics can
    // compute a total by grouping on this ID (note: requires `eventLabel` to
    // be a dimension in your report).
    event_label: id,
    // Google Analytics metrics must be integers, so the value is rounded.
    // For CLS the value is first multiplied by 1000 for greater precision
    // (note: increase the multiplier for greater precision if needed).
    value: Math.round(name === 'CLS' ? delta * 1000 : delta),
    // Use a non-interaction event to avoid affecting bounce rate.
    non_interaction: true,
  });
}

  addEventListener('DOMContentLoaded', function() {
      webVitals.getCLS(sendToGoogleAnalytics);
      webVitals.getFID(sendToGoogleAnalytics);
      webVitals.getLCP(sendToGoogleAnalytics);
   });
 </script>

GTM 抱怨:第 3 行错误,字符 38:此语言功能仅支持 ECMASCRIPT6 或更好的模式:对象解构。

我认为问题出在函数调用上。我尝试将函数修改为:

var sendToGoogleAnalytics = function({name, delta, id}){...

看来这不是问题。有人能指出 linter 不喜欢什么吗?

【问题讨论】:

    标签: javascript google-tag-manager web-vitals


    【解决方案1】:

    您需要使用变量名作为参数,然后访问引用该变量名的属性。

    function sendToGoogleAnalytics (data) {
    ...
    gtag('event', data.name, {
    ...
    

    【讨论】:

      【解决方案2】:

      如果您在 GTM 中测量 Web Vitals,我会推荐 Simo Ahava 在此处概述的方法:https://www.simoahava.com/analytics/track-core-web-vitals-in-ga4-with-google-tag-manager/

      他为您上面引用的代码编写了一个自定义模板,因此您不必担心如何安装它。

      【讨论】:

        猜你喜欢
        • 2019-09-03
        • 1970-01-01
        • 2021-01-31
        • 2021-12-29
        • 1970-01-01
        • 2021-05-17
        • 2020-11-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多