Form Abandonment Tracking In Google Analytics 4

Using Google Tag Manager

September 22, 2022

By Theresa Gutierrez

Tracking Form Abandonments With Google Tag Manager

Tracking form abandonment events in Google Analytics 4 (GA4) using Google Tag Manager (GTM) is a valuable metric to optimize your conversion rates. With websites using forms to collect high-quality leads, it is important to optimize our lead generation By tracking the activity on your website forms, you can analyze user behaviour and see if and where they are dropping off using each field of the form.

There are a number of different tools you can use to measure a form’s conversion rate, but we will be focusing on sending our data from Google Tag Manager to GA4.

We will use this blog to create a form abandonment listener using Google Tag Manager. If a form is abandoned by a visitor closing the browser tab or proceeding to another page.

Getting Started With Form Abandonment Events In GTM

Before we continue configuring our form abandonment events, we must ensure we are set up to track form submissions as well. If you need some help setting up your form submission tags, read our blog here.

In today’s blog, we will cover the following:

We will use this blog to create a form abandonment listener using Google Tag Manager. If a form is abandoned by a visitor closing the browser tab or proceeding to another page, the form listener will fire a dataLayer event.

Enabling Form Abandonment Variables

Before we begin configuring our form abandonment tags we need to create two User-Defined variables:

  • eventAction
  • eventCategory

By creating these two variables, our custom JavaScript tag will push these two variables into the dataLayer.

“event” is the name of the event we will be listening for

“eventCategory” is the name we are using to label this event

“eventAction” resolves to a ‘breadcrumb’ of fields that were interacted with on the form

Follow these steps to create these variables:

1. Navigate to the Variables section in GTM

2. Under the User-Defined Variables click New

3. Select Data Layer Variable for the variable type

4. Indicate eventAction as the Data Layer Variable Name

Google Tag Manager form abandonment eventAction variable configuration

5. Name your variable and click Save

6. Repeat for the eventCategory variable

Google Tag Manager form abandonment eventCategory variable configuration

Form Abandonment Trigger Setup

Creating our form abandonment trigger is very simple:

1. Navigate to the Trigger tab in the left hand menu

2. Click New

3. Select Custom Event from the list of trigger types

4. Name the event formAbandonment

5. Indicate that this event fires on All Custom Events

6. Name your trigger and click Save

Google Tag Manager form abandonment trigger configuration

Our Javascript pushes a formAbandonment event to the dataLayer, thus we must create a Trigger that listens out for that event name. We will use this Trigger to activate the GA4 Form Abandonment Tag we will define later in this blog.


window.dataLayer.push({
          'event' : 'formAbandonment',
          'eventCategory' : 'Form Abandonment',
          'eventAction' : it.history.join(" > ")
        })

Configuring Form Abandonment Tags

The form abandonment requires two different tags:

  • Script - Form Abandonment
  • GA4 Event - Form Abandonment

Script - Form Abandonment

This tag injects custom Javascript, to specific pages - in this case all the pages, that will potentially fire the form abandonment trigger. When the page is navigated away, it determines whether there is a form on the page that has fields that have been interacted with and no submit event has been fired related to it. The form fields are considered interacted with after a minimum of one character has been inputted. The eventAction field contains the breadcrumb of whatever fields were interacted with on the form, which we created as a dataLayer variable earlier in this blog.

Follow these steps to create the Form Abandonment Script Tag:

1. Navigate to the Tags section of GTM

2. Click New

3. Select the Custom HTML tag type

4. Paste the following code in the HTML field below:


<script>
(function() {
  if (typeof document.querySelectorAll === "undefined") {
    return
  }
    window.addEventListener('beforeunload', function(e) {
      findUnsubmittedForms().forEach(function(it) {
        window.dataLayer.push({
          'event' : 'formAbandonment',
          'eventCategory' : 'Form Abandonment',
          'eventAction' : it.history.join(" > ")
        })
      })
    })

    var history = {}

      document.addEventListener("change", function(e) {
        var target = e.target
        
        if (target && target.tagName && (target.tagName.toUpperCase() == "INPUT" || target.tagName.toUpperCase() == "TEXTAREA" || target.tagName.toUpperCase() == "SELECT")) {
		  var readableName = getNiceFieldName(target)
          var form = target.form
          if (form && readableName) {
            
            var formName = form.getAttribute("id")
            if (typeof history[formName] == "undefined") {
              history[formName] = []
            }
            if (history[formName].slice(-1) != readableName) {
              history[formName].push(readableName)
            }
          }
        }
    })

    function findUnsubmittedForms() {
      return Object.keys(history).filter(hasNoFormSubmitEvent(window.dataLayer)).map(findFormFromHistory).filter(notEmpty)
    }

    function hasNoFormSubmitEvent(dataLayer) {
      return function(id) {
        return dataLayer.filter(isFormSubmitEvent).map(getFormName).indexOf(id) == -1
      }
    }

    function isFormSubmitEvent(e) {
      return (e.event === 'gtm.formSubmit' && e['gtm.elementUrl'] !== 'https://www.facebook.com/tr/')
    }

    function getFormName(e) {
      return e['gtm.elementId']
    }

    function findFormFromHistory(id) {
      return {
        name: id,
        history: (history[id] || [])
      }
    }

    function notEmpty(form) {
      return form.history.length > 0
    }
	
	function getNiceFieldName(target) {
		var fieldLabel = findFieldLabel(target)
		if (fieldLabel) {
			return fieldLabel;
		}
		
		var fieldTitle = findFieldTitle(target);
		if (fieldTitle) {
			return fieldTitle;
		}
		
		return findInputName(target);
	}
	
	function findFieldLabel(target) {
		var inputId = target.getAttribute("id");
		var label = document.querySelector('[for="' + inputId + '"]');
		if (label) {
			return label.innerHTML.trim();
		}
    }
	
	function findFieldTitle(target) {
		var container = target.closest('.field-border');
		if (container) {
			return container.querySelector('.field-title').innerHTML.trim();
		}
    }
	
	function findInputName(target) {
		return target.getAttribute("name")
    }
})()
</script>

5. Name your tag and click Save

Google Tag Manager form abandonment script tag configuration

GA4 Event - Form Abandonment

This is the tag that gets fired whenever the Form Abandonment custom trigger is activated. The eventCategory field is saved as the category. The list of interacted form fields eventAction are saved as the action. The page url is saved in the label parameter.

Here’s how to configure the tag:

1. Navigate to the Tags section of GTM

2. Click New

3. Select the Google Analytics: GA4 Event

4. Connect the GA4 Configuration tag

5. Name the event - in this case, we named it GA4 Event - Form Abandonment

6. Add the following parameters

The eventCategory field is saved as the category. The list of interacted form fields eventAction are saved as the action. The page url is saved in the label parameter.

7. Name your tag and click Save

Google Tag Manager form abandonment tag configuration

Google Tag Manager solutions banner for Fishtank services

Testing Form Abandonment Tags In GTM

Be sure to test your tags in GTM’s Tag Assistant by clicking Preview in the top right corner of your workspace.

In a new tab in your browser, open your GA4 property. Navigate to the Configure tab in the left menu. Click Debug mode and go back to your Tag Assistant tab to begin testing.

After loading your tag assistant, be sure to refresh the page where your form is located. Test the tag by filling out some of the fields and navigate away from the form page to fire our trigger.

When testing your form abandonment tags, be sure to test the form by filling out the form completely and submitting it. This is so that you can confirm your form abandonment tag doesn’t fire when a form is completed. Instead, we want our form_submission tag to fire. If you need help setting up your form submission tags, check out our blog here.

The complexity of form abandonment and submission tracking can be daunting, but our friendly team is ready to help! Reach out to us at [email protected] if you have any questions.

Until then, happy tracking!

Theresa

Theresa Gutierrez

Sitecore Strategist | Sitecore Strategy MVP

Theresa, aka 'T', is a high-energy marketing creative with 8+ years of experience across various industries. She's passionate about delivering strategy and design, with a focus on Sitecore SaaS technologies. T is an avid golfer and loving dog momma, appeased only by delicious food and a bevy of something bubbly. Cheers!