GA4 Custom Event Tracking with addEventListener

Google Analytics BCS 3 years ago (2023-01-28) 999 Views 0 Comments
文章目录[隐藏]

Update time: January 13, 2025

This guide explains how to implement event tracking using JavaScript’s addEventListener() inside Google Tag Manager (GTM), and send interactions into Google Analytics 4 (GA4) via the dataLayer.

Unlike standard GTM click triggers, this approach gives you full control over non-standard, dynamic, or behavior-based interactions.

However, it also introduces common pitfalls—especially around DOM timing, SPA navigation, and trigger mismatches—which we’ll cover in detail.

Why addEventListener Still Matters in 2026

Even with improved GTM click triggers, addEventListener is still essential when:

  • Elements are dynamically rendered (React, Vue, Angular)
  • You need to track non-DOM-native interactions
  • GTM click triggers fail due to event bubbling issues
  • You want custom logic before sending data to GA4
  • You need to normalize inconsistent UI behavior across pages

How It Works

The tracking flow looks like this:

User Interaction
      ↓
addEventListener (JavaScript)
      ↓
dataLayer.push({ event: "custom_event" })
      ↓
GTM Custom Event Trigger
      ↓
GA4 Event Tag
      ↓
GA4 Reports / DebugView

Use Case Example

We will simulate a bookmark action using a keyboard shortcut or UI trigger.

Step 1: Custom HTML Tag (JavaScript Listener)

In GTM , click「Tags」——「New」——「Choose a tags type to begin setup…」——「Custom HTML」,Name it “HTML-Boomark”, and make the following settings:GA4 Custom Event Tracking with addEventListener

Source Code:

<script type="text/javascript">   
  document.addEventListener('keydown', function(event) {
 
  var isCtrlOrCmd = event.ctrlKey || event.metaKey;
  var isDKey = event.key === 'd' || event.key === 'D';

  if (isCtrlOrCmd && isDKey) {
     dataLayer.push({'event':'AddtoBookmark'});
  }
});
  
  
</script>

 

 

Step 2: Create a Custom Event Trigger in GTM

In GTM , click「Triggers」——「New」——「Choose a trigger type to begin setup…」——「Custom Event」,Name it “Bookmark”, and make the following settings:

GA4 Custom Event Tracking with addEventListener

 

 

Step 3: Create GA4 Event Tag

In GTM , click「Tags」——「New」——「Choose a tags type to begin setup…」——「Google Analytics: GA4 Event」,Name it “GA4-Event-AddtoBookmark”, and make the following settings:GA4 Custom Event Tracking with addEventListener

The event name is AddtoBookmark

Step 4: Test Using GTM Preview Mode

Next is preview debugging.

GA4 Custom Event Tracking with addEventListener

Tags is triggered and can be published.

 

 

Step 5: Verify Data in GA4 Reports

Generally, after 24 hours, we can see the data in GA4, such as:GA4 Custom Event Tracking with addEventListener

 

 

Like (0)
Post my comment
Cancel comment
Expression Bold Strikethrough Center Italic

Hi, you need to fill in your nickname and email!

  • Nickname (required)
  • Email (required)
  • Website