Skip to content

Commit

Permalink
Add support for GA4 setup through GTM and the window.dataLayer
Browse files Browse the repository at this point in the history
  • Loading branch information
mehigh committed Jul 28, 2024
1 parent c1f8765 commit ef68a84
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions js/src/send-to-analytics.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,7 @@
* limitations under the License.
*/

function getDeliveryFunction( type ) {
// eslint-disable-next-line no-console
return window[ type ] || console.log;
}
/* global gtag */

export function sendToAnalytics( { name, value, delta, id, attribution, rating } ) {
const analyticsData = window.webVitalsAnalyticsData?.[ 0 ] ?? null;
Expand Down Expand Up @@ -76,6 +73,16 @@ export function sendToAnalytics( { name, value, delta, id, attribution, rating }
}

if ( analyticsData && analyticsData.ga4_id ) {
getDeliveryFunction( 'gtag' )( 'event', name, eventParams );
if ( typeof gtag === 'function' ) {
gtag( 'event', name, eventParams );
} else if ( window.dataLayer && typeof window.dataLayer.push === 'function' ) {
window.dataLayer.push( {
event: name,
...eventParams,
} );
} else {
// eslint-disable-next-line no-console
console.log( 'Event:', name, eventParams );
}
}
}

0 comments on commit ef68a84

Please sign in to comment.