Adding analytics.js to Your Site

Adding analytics.js to Your Site

The analytics.js library is a JavaScript library for measuring how users interact with your website. This document explains how to add analytics.js to your site.

The JavaScript measurement snippet

Adding the following code (known as the "JavaScript measurement snippet") to your site's templates is the easiest way to get started using analytics.js.

The code should be added near the top of the  tag and before any other script or CSS tags, and the string 'GA_MEASUREMENT_ID' should be replaced with the property ID (also called the "measurement ID") of the Google Analytics property you wish to work with.

Tip: If you do not know your property ID, you can use the Account Explorer to find it.

 



The above code does four main things:

  1. Creates a 

    What data does the tracking snippet capture?

    When you add either of these tracking snippets to your website, you send a pageview for each page your users visit. Google Analytics processes this data and can infer a great deal of information including:

    • The total time a user spends on your site.
    • The time a user spends on each page and in what order those pages were visited.
    • What internal links were clicked (based on the URL of the next pageview).

    In addition, the IP address, user agent string, and initial page inspection analytics.js does when creating a new tracker is used to determine things like the following:

    • The geographic location of the user.
    • What browser and operating system are being used.
    • Screen size and whether Flash or Java is installed.
    • The referring site.

    Next steps

    For basic reporting needs, the data collected via the JavaScript tracking snippet can suffice, but in many cases there are additional questions you want answered about your users.

    The guides on this site explain how to track the interactions you care about with analytics.js, but before implementing a particular feature, it's highly recommended that you read the guides listed under the Fundamentals section in the left-side navigation. These guides will give you a high-level overview of the analytics.js library and help you better understand the code examples used throughout the site.

    How analytics.js Works

    Almost everything you need to track with analytics.js can be done using the ga() command queue. This guide explains what the command queue is, how it works, and how to execute commands to track user interactions.

    The ga command queue

    The JavaScript tracking snippet defines a global ga function known as the "command queue". It's called the command queue because rather than executing the commands it receives immediately, it adds them to a queue that delays execution until the analytics.js library is fully loaded.

    In JavaScript, functions are also objects, which means they can contain properties. The tracking snippet defines a qproperty on the ga function object as an empty array. Prior to the analytics.js library being loaded, calling the ga()function appends the list of arguments passed to the ga() function to the end of the q array.

    For example, if you were to run the tracking snippet and then immediately log the contents of ga.q to the console, you'd see an array, two items in length, containing the two sets of arguments already passed to the ga() function:

     

    console.log(ga.q);

    // Outputs the following:
    // [
    //   ['create', 'UA-XXXXX-Y', 'auto'],
    //   ['send', 'pageview']
    // ]

    Once the analytics.js library is loaded, it inspects the contents of the ga.q array and executes each command in order. After that, the ga() function is redefined, so all subsequent calls execute immediately.

    This pattern allows developers to use the ga() command queue without having to worry about whether or not the analytics.js library has finished loading. It provides a simple, synchronous-looking interface that abstracts away most of the complexities of asynchronous code.

    Adding commands to the queue

    All calls to the ga() command queue share a common signature. The first parameter, the "command", is a string that identifies a particular analytics.js method. Any additional parameters are the arguments that get passed to that method.

    The method a particular command refers to can be a global method, like create, a method on the ga object, or it can be an instance method on a tracker object, like send. If the ga() command queue receives a command it doesn't recognize, it simply ignores it, making calls to the ga() function very safe, as they will almost never result in an error.

    For a comprehensive list of all commands that can be executed via the command queue, see the ga() command queue reference.

    Command parameters

    Most analytics.js commands (and their corresponding methods) accept parameters in a number of different formats. This is done as a convenience to make it easier to pass commonly used fields to certain methods.

    As an example, consider the two commands in the JavaScript tracking snippet:

     

    ga('create', 'UA-XXXXX-Y', 'auto');
    ga('send', 'pageview');

    In the first command, create accepts the fields trackingIdcookieDomain, and name to optionally be specified as the second, third, and fourth parameters, respectively. The send command accepts an optional hitType second parameter.

    All commands accept a final fieldsObject parameter that can be used to specify any fields as well. For example, the above two commands in the tracking snippet could be rewritten as:

     

    ga('create', {
      trackingId: 'UA-XXXXX-Y',
      cookieDomain: 'auto'
    });
    ga('send', {
      hitType: 'pageview'
    });

    See the ga() command queue reference for a comprehensive list of the optional parameters allowed for each of the commands.

    Next steps

    After reading this guide you should have a good understanding of how to execute commands with analytics.js, and how the command queue works. The next guide will cover how to create tracker objects.

    Creating Trackers

    Tracker objects (also known as "trackers") are objects that can collect and store data and then send that data to Google Analytics.

    When creating a new tracker, you must specify a tracking ID (which is the same as the property ID that corresponds to one of your Google Analytics properties) as well as a cookie domain, which specifies how cookies are stored. (The recommended value 'auto' specifies automatic cookie domain configuration.)

    If a cookie does not exist for the specified domain, a client ID is generated and stored in the cookie, and the user is identified as new. If a cookie exists containing a client ID value, that client ID is set on the tracker, and the user is identified as returning.

    Upon creation, tracker objects also gather information about the current browsing context such as the page title and URL, and information about the device such as screen resolution, viewport size, and document encoding. When it's time to send data to Google Analytics, all of the information currently stored on the tracker gets sent.

    The create method

    The analytics.js library provides a variety ways to create trackers, but the most common way is to use the createcommand and pass the tracking ID and cookie domain fields as the second and third parameters:

     

    ga('create', 'UA-XXXXX-Y', 'auto');

    Naming trackers

    You may also, optionally, name the tracker by passing the name field as the fourth argument in the create command. Naming a tracker is necessary in cases where you need to create more than one tracker for the same page. For more details on why you might need to do this, see the section below on working with multiple trackers.

     

    ga('create', 'UA-XXXXX-Y', 'auto', 'myTracker');

    Creating a tracker without setting the name field is known as creating a "default" tracker. A default tracker is internally given the name "t0".

    Specifying fields at creation time

    An optional fields object may also be passed that allows you to set any of the analytics.js fields at creation time, so they will be stored on the tracker and apply to all hits that are sent.

     

    ga('create', 'UA-XXXXX-Y', 'auto', 'myTracker', {
      userId: '12345'
    });

    And as with all calls to the ga() function, the fields object may also be used to specify all of the fields together:

     

    ga('create', {
      trackingId: 'UA-XXXXX-Y',
      cookieDomain: 'auto',
      name: 'myTracker',
      userId: '12345'
    });

    See the create method reference for more comprehensive details.

    Working with multiple trackers

    In some cases you might want to send data to multiple properties from a single page. This is useful for sites that have multiple owners overseeing sections of a site; each owner could view their own property.

    To track data for two separate properties, you need to create two separate trackers, and at least one of them must be a named tracker. The following two commands create a default tracker and a tracker named "clientTracker":

     

    ga('create', 'UA-XXXXX-Y', 'auto');
    ga('create', 'UA-XXXXX-Z', 'auto', 'clientTracker');

    Running commands for a specific tracker

    To run analytics.js commands for a specific tracker, you prefix the command name with the tracker name, followed by a dot. When you don't specify a tracker name, the command is run on the default tracker.

    To send pageviews for the above two trackers, you'd run the following two commands:

     

    ga('send', 'pageview');
    ga('clientTracker.send', 'pageview');

    Future guides will go into more detail on the syntax for running specific commands. You can also refer to the command queue reference to see the full command syntax for all analytics.js commands.

    Next steps

    Once you've created a tracker, you may need to access the data stored on that tracker object. The next guide explains how to get and set tracker data.

    Getting and Setting Field Data

    Getting and setting field data on a tracker sometimes requires having a reference to the tracker object itself. Since commands added to the ga() command queue execute asynchonously and do not return a value, and since trackers are most commonly created using the create command, getting a reference to a tracker object requires waiting until after the create command has been executed. You can do this via the ready callback.

    The ready callback

    The ready callback is a function that you can add to the ga() command queue. The function will be invoked as soon as the analytics.js library is fully loaded, and all previous commands added to the queue have been executed.

    Since all commands to the queue are executed in order, adding a ready callback to the queue after adding a createcommand will ensure that the ready callback is executed after the tracker has been created. If a default tracker has been created when a ready callback is invoked, it is passed as the callback's first (and only) argument.

    The following code shows how to access the default tracker object and log it to the console:

     

    ga('create', 'UA-XXXXX-Y', 'auto');

    ga(function(tracker) {
      // Logs the tracker created above to the console.
      console.log(tracker);
    });

    Getting trackers via ga Object methods

    If you're not using a default tracker, or if you have more than one tracker on the page, you can access those trackers via one of the ga object methods.

    Once the analytics.js library is fully loaded, it adds additional methods to the ga object itself. Two of those methods, getByName and getAll, are used to access tracker objects.

    Note: ga object methods are only available when analytics.js has fully loaded, so you should only reference them inside a ready callback.

    getByName

    If you know the name of the tracker you want to access, you can do so using the getByName method:

     

    ga('create', 'UA-XXXXX-Y', 'auto', 'myTracker');

    ga(function() {
      // Logs the "myTracker" tracker object to the console.
      console.log(ga.getByName('myTracker'));
    });

    getAll

    To get an array of all created trackers, use the getAll method:

     

    ga('create', 'UA-XXXXX-Y', 'auto', 'tracker1');
    ga('create', 'UA-XXXXX-Z', 'auto', 'tracker2');

    ga(function() {
      // Logs an array of all tracker objects.
      console.log(ga.getAll());
    });

    Getting data stored on a tracker

    Once you have a reference to a tracker object, you can use its get method to access the value of any field currently stored on the tracker.

     

    ga('create', 'UA-XXXXX-Y', 'auto');

    ga(function(tracker) {
      // Logs the trackers name.
      // (Note: default trackers are given the name "t0")
      console.log(tracker.get('name'));

      // Logs the client ID for the current user.
      console.log(tracker.get('clientId'));

      // Logs the URL of the referring site (if available).
      console.log(tracker.get('referrer'));
    });

    Update data

    Tracker objects can be updated using the set method. A tracker's set method can be called on a tracker object itself or by adding a set command to the ga() command queue.

    Since getting a reference to a tracker object requires using the ready callback, using the ga() command queue is the recommended way to update a tracker.

    The ga() command queue

    The set command can be invoked in two ways: by passing two parameters, a field and its corresponding value, or by passing an object of field/value pairs.

    The following example sets the page field to '/about' on the default tracker:

     

    ga('set', 'page', '/about');

    This example sets the page and title fields at the same time:

     

    ga('set', {
      page: '/about',
      title: 'About Us'
    });

    Using a named tracker

    If you're using a named tracker instead of the default tracker, you can pass its name in the command string.

    The following call sets the page field on the tracker named "myTracker":

     

    ga('myTracker.set', 'page', '/about');

    On the tracker object itself

    If you have a reference to the tracker object, you can call that tracker's set method directly:

     

    ga(function(tracker) {
      tracker.set('page', '/about');
    });

    Note: tracker objects do not update themselves. If a user changes the size of the window, or if code running on the page updates the URL, tracker objects do not automatically capture this information. In order for the tracker object to reflect these changes, you must manually update it.

    Ampersand syntax

    Tracker fields are usually get and set using their field names. (Refer to the field reference for a complete list of analytics.js fields and their names.)

    An alternative way to get and set fields is to refer to them by their corresponding Measurement Protocol parameter names names.

    For example, the following two console.log expressions both log the document title to the console:

     

    ga(function(tracker) {
      // Gets the title using the analytics.js field name.
      console.log(tracker.get('title'));

      // Gets the title using the measurement protocol
      // parameter name, prefixed with an ampersand.
      console.log(tracker.get('&dt'));
    });

    In general, ampersand syntax is not recommended and should only be used when the analytics.js field name for a Measurement Protocol parameter does not exist (this occassionally happens if a new feature is added to the Measurement Protocol before it is implemented in analytics.js).

    Next steps

    Now that you know how to create trackers and update the data stored on them, the next step is to learn how to send that data to Google Analytics for processing.

    Sending Data to Google Analytics

    The last line of the JavaScript measurement snippet adds a send command to the ga() command queue to send a pageview to Google Analytics:

     

    ga('create', 'UA-XXXXX-Y', 'auto');
    ga('send', 'pageview');

    The object that is doing the sending is the tracker that was scheduled for creation in the previous line of code, and the data that gets sent is the data stored on that tracker.

    This guide describes the various ways to send data to Google Analytics and explains how to control what data gets sent.

    Hits, hit types, and the Measurement Protocol

    When a tracker sends data to Google Analytics it's called sending a hit, and every hit must have a hit type. The JavaScript tracking snippet sends a hit of type pageview; other hit types include screenvieweventtransactionitemsocialexception, and timing. This guide outlines the concepts and methods common to all hit types. Individual guides for each hit type can be found under the section Tracking common user interactions in the left-side navigation.

    The hit is an HTTP request, consisting of field and value pairs encoded as a query string, and sent to the Measurement Protocol.

    If you have your browser's developers tools open when you load a page that uses analytics.js, you can see the hits being sent in the network tab. Look for requests sent to google-analytics.com/collect.

    What data gets sent

    When sending a hit to the Measurement Protocol, trackers send all of the fields that are currently stored and are valid Measurement Protocol parameters. For example, fields like title and location are sent but cookieDomain and hitCallback are not.

    In some cases, you want to send fields to Google Analytics for the current hit but not for any subsequent hits. An example of this is an event hit where the eventAction and eventLabel fields are relevant to the current hit only.

    To send fields with the current hit only, you can pass them as arguments to the send method. To have field data sent with all subsequent hits, you should update the tracker using the set method.

    The send method

    A tracker's send method can be called directly on the tracker object itself or by adding a send command to the ga()command queue. Since most of the time you don't have a reference to the tracker object, using the ga() command queue is the recommended way to send tracker data to Google Analytics.

    Using the ga() command queue

    The signature for adding a send command to the ga() command queue is as follows:

     

    ga('[trackerName.]send', [hitType], [...fields], [fieldsObject]);

    As mentioned above, the values specified via in the hitType...fields, and fieldsObject parameters get sent for the current hit only. They do not get stored on the tracker object, nor are they sent with subsequent hits.

    If any of the fields passed with the send command are already set on the tracker object, the values passed in the command will be used rather than the values stored on the tracker.

    Calls to the send command must specify a hitType and, depending on the type specified, other parameters may be required as well. See the individual guides for tracking common user interactions in the left-side navigation for more details.

    The simplest way to use the send command, that works for all hit types, is to pass all fields using the fieldsObjectparameter. For example:

     

    ga('send', {
      hitType: 'event',
      eventCategory: 'Video',
      eventAction: 'play',
      eventLabel: 'cats.mp4'
    });

    For convenience, certain hit types allow commonly used fields to be passed directly as arguments to the sendcommand. For example, the above send command for the "event" hit type could be rewritten as:

     

    ga('send', 'event', 'Video', 'play', 'cats.mp4');

    For a complete list of what fields can be passed as arguments for the various hit types, see the "parameters" section of the send method reference.

    Using a named tracker

    If you're using a named tracker instead of the default tracker, you can pass its name in the command string.

    The following send command will be called on the tracker named "myTracker":

     

    ga('myTracker.send', 'event', 'Video', 'play', 'cats.mp4');

    On the tracker object itself

    If you have a reference to the tracker object, you can call that tracker's send method directly:

     

    ga(function(tracker) {
      tracker.send('event', 'Video', 'play', 'cats.mp4');
    });

    Knowing when the hit has been sent

    In some cases you need to know when a hit is done being 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 page starts unloading, which means your analytics.js commands to send hits may never run.

    An example of this is when you want to send an event to Google Analytics to record that a user clicked on a form's submit button. In most cases, clicking the submit button will immediately start loading the next page, and any ga('send', ...) commands will not run.

    The solution to this is to intercept the event to stop the page from unloading. You can then send your hit to Google Analytics as usual, and once the hit is done being sent, you can resubmit the form programmatically.

    hitCallback

    To be notified when a hit is done sending, you set the hitCallback field. hitCallback is a function that gets called as soon as the hit has been successfully sent.

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

     

    // 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.
      ga('send', 'event', 'Signup Form', 'submit', {
        hitCallback: function() {
          form.submit();
        }
      });
    });

    Handling timeouts

    The above example works nicely, but it has one serious problem. If (for whatever reason) the analytics.js library fails to load, the hitCallback function will never run. And if the hitCallback function never runs, users will never be able to submit the form.

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

    The next example updates the above code to use a timeout. If one second passes after the user clicks the submit button and the hitCallback 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 `hitCallback` 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.
      ga('send', 'event', 'Signup Form', 'submit', {
        hitCallback: submitForm
      });
    });

    If you're using the above pattern in many places throughout your site, it's probably easier to 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 invokes 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 easily wrap all hitCallback functions with a timeout to ensure your site works as expected even in cases where your hits fail to send or the analytics.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.
      ga('send', 'event', 'Signup Form', 'submit', {
        hitCallback: createFunctionWithTimeout(function() {
          form.submit();
        })

      });
    });

    Specifying different transport mechanisms

    By default, analytics.js picks the HTTP method and transport mechanism with which to optimally send hits. The three options are 'image' (using an Image object), 'xhr' (using an XMLHttpRequest object), or 'beacon' using the new navigator.sendBeacon method.

    The former two methods share the problem described in the previous section (where hits are often not sent if the page is being unloaded). The navigator.sendBeacon method, by contrast, is a new HTML feature created to solve this problem.

    If your user's browser supports the navigator.sendBeacon, you can specify 'beacon' as the transport mechanism and not have to worry about setting a hit callback.

    The following code sets the transport mechanism to 'beacon' in browsers that support it.

     

    ga('create', 'UA-XXXXX-Y', 'auto');

    // Updates the tracker to use `navigator.sendBeacon` if available.
    ga('set', 'transport', 'beacon');

    Currently, analytics.js only uses navigator.sendBeacon if the transport mechanism is set to 'beacon'. However, in the future, analytics.js will likely switch to using 'beacon' as the default mechanism in browsers that support it.

    Next steps

    Measuring certain types of user interactions can sometimes require complex implementations. However, in many cases these implementations have already been developed and made available as analytics.js plugins. The next guide explains how to use analytics.js plugins with the ga() command queue.

    Using Plugins

    Plugins are scripts that enhance the functionality of analytics.js to aid in measuring user interaction. Plugins are typically specific to a set of features that may not be required by all Google Analytics users, such as ecommerce or cross-domain tracking, and are therefore not included in analytics.js by default.

    This guide explains how to require and use analytics.js plugins.

    Requiring plugins

    The require command takes the name of a plugin and registers it for use with the ga() command queue. If the plugin accepts configuration options, those options can be passed as the final argument to the require command.

    The following is the full require command's signature:

     

    ga('[trackerName.]require', pluginName, [pluginOptions]);

    For example, here is how you would require the Enhanced Ecommerce plugin for use with the default tracker:

     

    ga('require', 'ec');

    And here is how you would require the Display Features plugin for a tracker named "myTracker" and pass a configuration option that overrides the default cookie name value:

     

    ga('myTracker.require', 'displayfeatures', {
      cookieName: 'display_features_cookie'
    });

    Loading the plugin code

    The require command initializes the plugin methods for use with the ga() command queue, but it does not load the plugin script itself. If you're using a third-party plugin, or writing a plugin yourself, you'll need to manually add the plugin code to the page.

    The recommended method for adding plugin code to the page is via a 


    Note: Official Google Analytics plugins for analytics.js get loaded automatically when they're required; you do not need to add script tags for them. The complete list of official analytics.js plugins can be found under the Offical plugins section in the left-side navigation.

    Waiting for plugins to load

    Because both the analytics.js library and analytics.js plugins are loaded asynchronously, it can be a challenge to know when plugins are fully loaded and ready to be used.

    The analytics.js library solves this problem by halting the execution of the command queue when it encounters a require command for a plugin that isn't yet loaded. Once the plugin is loaded, queue execution continues as normal.

    As a result, it's extremely important that you test the plugins you're using to ensure they load and run correctly. If a plugin fails to load or has an error, it will prevent all subsequent analytics.js commands from executing.

    Calling plugin methods

    After requiring a plugin, it's methods become available for use with the ga() command queue. Here is the command signature for calling plugin methods:

     

    ga('[trackerName.][pluginName:]methodName', ...args);

    For example, the Enhanced Ecommerce plugin's addProduct method can be called like this:

     

    ga('ec:addProduct', {
      'id': 'P12345',
      'quantity': 1
    });

    Or on a named tracker by adding the tracker name to the command string:

     

    ga('myTracker.ec:addProduct', {
      'id': 'P12345',
      'quantity': 1
    });

    Next steps

    If you've read all the guides in this section, you should be familiar with most of the features of analytics.js. The next guide explains how to debug your analytics.js implementations to more easily detect errors and see exactly what your code is doing.

    Debugging

    This guide explains how to use the debug version of the analytics.js library to ensure your implementations are working correctly.

    The debug version of the analytics.js library

    Google Analytics provides a debug version of the analytics.js library that logs detailed messages to the Javascript console as its running. These messages include successfully executed commands as well as warnings and error messages that can tell you when your tracking code is set up incorrectly. It also provides a breakdown of each hit sent to Google Analytics, so you can see exactly what data is being tracked.

    You can enable the debug version of analytics.js by changing the URL in the JavaScript tracking snippet from https://www.google-analytics.com/analytics.js to https://www.google-analytics.com/analytics_debug.js:

     

    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://www.google-analytics.com/analytics_debug.js','ga');

    ga('create', 'UA-XXXXX-Y', 'auto');
    ga('send', 'pageview');

    Note: The debug version of analytics.js should only be used during development and testing, as it's quite a bit larger than analytics.js and will slow down the loading of your page.

    Testing your implementation without sending hits

    The debug version of analytics.js will send data to Google Analytics exactly like the non-debug version. This allows you to visit a website running analytics.js code and inspect the implementation without interfering with the data being tracked.

    If you do not want to send data to Google Analytics in certain cases (e.g. development or testing environments), you can disable the sendHitTask task and nothing will be sent.

    When running on localhost, the following code will prevent any hits from being sent to Google Analytics:

     

    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://www.google-analytics.com/analytics_debug.js','ga');

    ga('create', 'UA-XXXXX-Y', 'auto');

    if (location.hostname == 'localhost') {
      ga('set', 'sendHitTask', null);
    }


    ga('send', 'pageview');

    Trace debugging

    Enabling trace debugging will output more verbose information to the console.

    To enable trace debugging, load the debug version of analytics.js as described above and add the following line of JavaScript to the tracking snippet prior to any calls to the ga() command queue.

     

    window.ga_debug = {trace: true};

    The full tracking snippet with trace debugging enabled is as follows:

     

    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://www.google-analytics.com/analytics_debug.js','ga');

    window.ga_debug = {trace: true};
    ga('create', 'UA-XXXXX-Y', 'auto');
    ga('send', 'pageview');

    The Google Analytics Debugger Chrome extension

    Google Analytics also provides a Chrome extension that can enable the debug version of analytics.js without requiring you to change your tracking code. This allows you to debug your own sites and also see how other sites have implemented Google Analytics tracking with analytics.js.

    Google Tag Assistant

    Google Tag Assistant is a Chrome Extension that helps you validate the tracking code on your website and troubleshoot common problems. It's an ideal tool for debugging and testing your analytics.js implementations locally and ensuring everything is correct before deploying your code to production.

    Tag Assistant works by letting you record a typical user flow. It keeps track of all the hits you send, checks them for any problems, and gives you a full report of the interactions. If it detects any issues or potential improvements, it will let you know.

     

    To learn more, visit the help center and read About Tag Assistant and About Tag Assistant Recordings. You can also watch this demo video that shows Tag Assistant being used to catch errors and check the validity of advanced tracking implementations such as cross-domain tracking.

你可能感兴趣的:(google,analytics)