Send data to Google Analytics with gtag.js

This page describes how to use gtag.js commands to send data from your site to Google Analytics.

Send data with the event command

Once you've added the global snippet to a web page, use the event command to send data to Google Analytics. For example, use the following event command to indicate that a user has signed in using their Google account:

gtag('event', 'login', {'method': 'Google'});

Learn more about the event command in the API reference.

Route data to groups and properties

You can send one set of tracking information to one or more Google Analytics property IDs, and another set of information to other property IDs. You can organize properties into groups and route data to them.

For example, the following code example illustrates how to route a sign_in event to a group 'agency' that includes two Google Analytics properties.

// Configure a target
gtag('config', 'GA-TRACKING_ID-1');
gtag('config', 'GA-TRACKING_ID-2', { 'groups': 'agency' });
gtag('config', 'GA-TRACKING_ID-3', { 'groups': 'agency' });

// Route this sign_in event to tracking IDs in the 'agency' group:
gtag('event', 'sign_in', { 'send_to': 'agency' });

Learn more about how to group and route data.

Know when an event has been sent

In some cases, you need to know when an event has been successfully sent to Google Analytics, so you can take action immediately afterward. This is common when you need to record a particular interaction that would take a user away from the current page. Many browsers stop executing JavaScript as soon as the next page starts loading, which means your gtag.js event commands may never run.

For example, you may want to send an event to Google Analytics to record that a user has clicked on a form's submit button. In most cases, clicking the submit button will immediately start loading the next page before any event commands have a chance to execute.

The solution is to intercept the event to stop the next page from loading so that you can send the event to Google Analytics. After the event has been sent, submit the form programmatically.

Implement event callback functions

You can implement an event callback function that gets called as soon as an event has been successfully sent.

The following example shows how to cancel a form's default submit action, send an event to Google Analytics, and then resubmit the form using the event callback function:

// Get a reference to the form element, assuming
// it contains the ID attribute "signup-form".
var form = document.getElementById('signup-form');

// Add a listener for the "submit" event.
form.addEventListener('submit', function(event) {

  // Prevent the browser from submitting the form
  // and thus unloading the current page.
  event.preventDefault();

  // Send the event to Google Analytics and
  // resubmit the form once the hit is done.
  gtag('event', 'signup_form_complete', {
    'event_callback': function() {
      form.submit();
    }
  });
});

Handle timeouts

There is one drawback to the above example: If the gtag.js library fails to load, the event callback function will never run and users will never be able to submit the form.

Whenever you put critical site functionality inside the event callback function, you should always use a timeout function to handle cases where the gtag.js library fails to load.

The following example enhances the above code to use a timeout. If one second passes after the user clicks the submit button and the event callback function has not run, the form is resubmitted anyway.

// Gets a reference to the form element, assuming
// it contains the ID attribute "signup-form".
var form = document.getElementById('signup-form');

// Adds a listener for the "submit" event.
form.addEventListener('submit', function(event) {

  // Prevents the browser from submitting the form
  // and thus unloading the current page.
  event.preventDefault();

  // Creates a timeout to call submitForm after one second.
  setTimeout(submitForm, 1000);

  // Keeps track of whether or not the form has been submitted.
  // This prevents the form from being submitted twice in cases
  // where the event callback function fires normally.
  var formSubmitted = false;

  function submitForm() {
    if (!formSubmitted) {
      formSubmitted = true;
      form.submit();
    }
  }

  // Sends the event to Google Analytics and
  // resubmits the form once the hit is done.
  gtag('event', 'signup_form_complete', { 'event_callback': {
    submitForm();
  }});
});

If you use the above pattern throughout your site, create a utility function to handle timeouts.

The following utility function accepts a function as input and returns a new function. If the returned function is called before the timeout period (the default timeout is one second), it clears the timeout and calls the input function. If the returned function isn't called before the timeout period, the input function is called regardless.

function createFunctionWithTimeout(callback, opt_timeout) {
  var called = false;
  function fn() {
    if (!called) {
      called = true;
      callback();
    }
  }
  setTimeout(fn, opt_timeout || 1000);
  return fn;
}

Now, you can wrap all event callback functions with a timeout to ensure your site works as expected, even in cases where your events fail to send or the gtag.js library never loads.

// Gets a reference to the form element, assuming
// it contains the ID attribute "signup-form".
var form = document.getElementById('signup-form');

// Adds a listener for the "submit" event.
form.addEventListener('submit', function(event) {

  // Prevents the browser from submitting the form
  // and thus unloading the current page.
  event.preventDefault();

  // Sends the event to Google Analytics and
  // resubmits the form once the hit is done.
  gtag('event', 'signup_form', { 'event_callback': {
    createFunctionWithTimeout(function() {
      form.submit();
    })
  }});
});

Specify different transport mechanisms

By default, gtag.js picks the HTTPS method and transport mechanism with which to optimally send hits. The three options are:

  • 'image' (using an Image object)
  • 'xhr' (using an XMLHttpRequest object)
  • 'beacon' (using the navigator.sendBeacon method)

The first two methods share the problem described in the previous section, where hits are not sent if the page is being unloaded. The navigator.sendBeacon method solves this problem by asynchronously transmitting hits to the web server without having to set a hit callback.

The following code sets the transport mechanism to 'beacon' for browsers that support it:

gtag('config', 'GA_TRACKING_ID', { 'transport_type': 'beacon'});