I'm trying to use GTM to send data from webVitals to google analytics.
Using this package: 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 is complaining: Error at line 3, character 38: This language feature is only supported for ECMASCRIPT6 mode or better: object destructuring.
I thought the issue was with the function call. I tried to modify the function to:
var sendToGoogleAnalytics = function({name, delta, id}){...
Seems that was not the issue. Can someone point out what the linter does not like?
You need to use a variable name as parameter and then access the attributes referenceing that variable name.
function sendToGoogleAnalytics (data) {
...
gtag('event', data.name, {
...