ga.js Basic Methods
_deleteCustomVar(index)
_getName()
_getAccount()
_getVersion()
_getVisitorCustomVar(index)
_initData()
deprecated_setAccount(accountID)
_setCookiePersistence(milliseconds)
deprecated_setCustomVar(index, name, value, opt_scope)
_setSampleRate(newRate)
_setSessionTimeout(newTimeout)
deprecated_setSessionCookieTimeout(cookieTimeoutMillis)
_setSiteSpeedSampleRate(sampleRate)
_setVar(newVal)
deprecated_setVisitorCookieTimeout(cookieTimeoutMillis)
_trackPageLoadTime()
deprecated_trackPageview(opt_pageURL)
Method Details
_deleteCustomVar()
_deleteCustomVar(index)
This method deletes the variable assigned to the supplied index, if one exists. For example, you might set a visitor-level custom variable and later decide that you no longer want to use this visitor-level variable.
Async Snippet (recommended)
_gaq.push(['_deleteCustomVar', 1]);
▸
Traditional (ga.js) Snippet
parameters
Int index
The index of the custom variable to delete.
_getName()
_getName()
Returns the name the tracker was given when it was created.
Async Snippet (recommended)
_gaq.push(function() {
var pageTracker = _gat._getTrackerByName(); // Gets the default tracker.
var trackerName = pageTracker._getName();
});
▸
Traditional (ga.js) Snippet
returns
String
The tracker's name.
_getAccount()
_getAccount()
Returns the Google Analytics ID for this tracker object. If you are tracking pages on your website in multiple accounts, you can use this method to determine the account that is associated with a particular tracker object.
Async Snippet (recommended)
_gaq.push(function() {
var pageTracker = _gat._getTrackerByName(); // Gets the default tracker.
var accountId = pageTracker._getAccount();
});
▸
Traditional (ga.js) Snippet
returns
String
Account ID this tracker object is instantiated with.
_getVersion()
_getVersion()
Returns the GATC version number.
Async Snippet (recommended)
_gaq.push(function() {
var pageTracker = _gat._getTrackerByName(); // Gets the default tracker.
var version = pageTracker._getVersion();
});
▸
Traditional (ga.js) Snippet
returns
String
GATC version number.
_getVisitorCustomVar()
_getVisitorCustomVar(index)
Returns the visitor level custom variable value assigned for the specified index.
Async Snippet (recommended)
_gaq.push(function() {
var pageTracker = _gat._getTrackerByName(); // Gets the default tracker.
var visitorCustomVar1Value = pageTracker._getVisitorCustomVar(1);
});
▸
Traditional (ga.js) Snippet
parameters
Int index
The index of the visitor level custom variable.
returns
String
The value of the visitor level custom variable. Returns undefined if unable to retrieve the variable for the specified index.
_initData()
_initData()
Deprecated. initData() now executes automatically in the ga.js tracking code.
Initializes or re-initializes the GATC (Google Analytics Tracker Code) object.
var pageTracker = _gat._getTracker("UA-12345-1");
pageTracker._trackPageview();
_setAccount()
_setAccount(accountId)
Used exclusively in asynchronous tracking. Sets the web property ID for the tracking object.
_gaq.push(['_setAccount', 'UA-XXXXX-X']);
parameters
String accountID
The full web property ID (e.g. UA-65432-1
) for the tracker object.
_setCookiePersistence()
_setCookiePersistence(milliseconds)
This method is deprecated. Please use _setVisitorCookieTimeout(cookieTimeoutMillis)
instead.
Sets the Google Analytics visitor cookie expiration in milliseconds. By default, the visitor cookie is set to expire in 2 years. If you prefer, you can change the expiration date of the visitor cookie using this method. For example, to set the expiration of the visitor cookie to 7 days you would use the following code:
pageTracker._setCookiePersistence(604800000);
parameters
Number milliseconds
New visitor cookie expiration time.
_setCustomVar()
_setCustomVar(index, name, value, opt_scope)
Sets a custom variable with the supplied name, value, and scope for the variable. There is a 128-byte character limit for the name
and value
combined.
Async Snippet (recommended)
_gaq.push(['_setCustomVar', 1, 'Section', 'Life & Style', 3]);
▸
Traditional (ga.js) Snippet
returns
Boolean
This method returns true
if the custom variable has been set successfully, and false
if it has not (e.g. if your name/value string length exceeds 128 bytes, or if you use an incorrect slot).
parameters
Int index
Required. The slot used for the custom variable. Possible values are 1-5
, inclusive.
String name
Required. The name for the custom variable.
String value
Required. The value for the custom variable.
Int opt_scope
Optional. The scope used for the custom variable. Possible values are 1
for visitor-level, 2
for session-level, and 3
for page-level.
_setSampleRate()
_setSampleRate(newRate)
Sets the new sample rate. If your website is particularly large and subject to heavy traffic spikes, then setting the sample rate ensures un-interrupted report tracking. Sampling in Google Analytics occurs consistently across unique visitors, so there is integrity in trending and reporting even when sampling is enabled, because unique visitors remain included or excluded from the sample, as set from the initiation of sampling.
You only need to specify this method at the same time that _setAccount() is called, typically once per page or application (wherever you initialize the tracking code itself). Keep in mind that the sample rate value you specify remains in effect for as long as the tracking object itself persists.
Async Snippet (recommended)
_gaq.push(['_setSampleRate', '2.5']);
▸
Traditional (ga.js) Snippet
parameters
String newRate
New sample rate to set. Provide a numeric string between 0 and 100 (precise to two decimal places).
_setSessionTimeout()
_setSessionTimeout(newTimeout)
This method is deprecated. Please use _setSessionCookieTimeout(cookieTimeoutMillis)
instead.
Sets the new session timeout in seconds. By default, session timeout is set to 30 minutes (1800 seconds). Session timeout is used to compute visits (see How a session is defined in Analytics). If you want to change the definition of a "session" for your particular needs, you can pass in the number of seconds to define a new value. This will impact the Visits reports in every section where the number of visits are calculated, and where visits are used in computing other values. For example, the number of visits will generally increase if you shorten the session timeout, and will generally decrease if you increase the session timeout.
parameters
String newTimeout
New session timeout to set in seconds.
_setSessionCookieTimeout()
_setSessionCookieTimeout(cookieTimeoutMillis)
Sets the new session cookie timeout in milliseconds. By default, session timeout is set to 30 minutes. Session timeout is used to compute visits, since a visit ends after 30 minutes of browser inactivity or upon browser exit. If you want to change the definition of a "session" for your particular needs, you can pass in the number of milliseconds to define a new value. This will impact the Visits reports in every section where the number of visits are calculated, and where visits are used in computing other values. For example, the number of visits will increase if you shorten the session timeout, and will decrease if you increase the session timeout. You can change the expiration timeout to 0 to indicate that this cookie should be deleted when the browser is closed.
Async Snippet (recommended)
_gaq.push(['_setSessionCookieTimeout', 1800000]);
▸
Traditional (ga.js) Snippet
parameters
Number cookieTimeoutMillis
New session timeout in milliseconds or 0 to delete the cookie when the browser is closed.
_setSiteSpeedSampleRate()
_setSiteSpeedSampleRate(sampleRate)
Defines a new sample set size for Site Speed data collection. By default, a fixed 1% sampling of your site visitors make up the data pool from which the Site Speed metrics are derived. If you have a relatively small number of daily visitors to your site, such as 100,000 or fewer, you might want to adjust the sampling to a larger rate. This will provide increased granularity for page load time and other Site Speed metrics. (See Site Speed in the Help Center for details about the Site Speed reports.)
The _setSiteSpeedSampleRate()
method must be called prior to _trackPageview()
in order to be effective.
Analytics restricts Site Speed collection hits for a single property to the greater of 1% of users or 10K hits per day in order to ensure an equitable distribution of system resources for this feature.
Note: We strongly encourage sites with greater than 1 million hits per day to keep their sample selection set to the default 1% rate. Adjusting the sample size to a larger number will not increase your sample size.
Async Snippet (recommended)
_gaq.push(['_setSiteSpeedSampleRate', 5]);
_gaq.push(['_trackPageview']);
▸
Traditional (ga.js) Snippet
parameters
Number sampleRate
Value between 0 - 100 to define the percentage of visitors to your site that will be measured for Site Speed purposes. For example, a value of 5
sets the Site Speed collection sample to 5%.
_setVisitorCookieTimeout()
_setVisitorCookieTimeout(cookieTimeoutMillis)
Sets the Google Analytics visitor cookie expiration in milliseconds. By default, the visitor cookie is set to expire in 2 years. If you prefer, you can change the expiration date of the visitor cookie using this method. You can change the expiration timeout to 0 to indicate that this cookie should be deleted when the browser is closed.
Async Snippet (recommended)
_gaq.push(['_setVisitorCookieTimeout', 63072000000]);
▸
Traditional (ga.js) Snippet
parameters
Number cookieTimeoutMillis
New visitor cookie expiration time in milliseconds or 0 to delete the cookie when the browser is closed.
_setVar()
_setVar(newVal)
This method is deprecated. Please use _setCustomVar()
instead.
Sets or defines a custom visitor segment with the supplied string. You can use this value to provide additional segmentation on users to your website. For example, you could have a login page or a form that triggers a value based on a visitor's input, such as a preference the visitor chooses, or a privacy option. This variable is then updated in the cookie for that visitor. When implemented on your site and data is collected via this method, the newly defined segment appears in the User Defined reports in the Visitors section of the Analytics Reports. Additionally, you can access the User Defined Value segment in the Content Detail report to see which percentage of visitors to a page belong to a particular segment that you define.
parameters
String newVal
New user defined value to set.
_trackPageLoadTime()
_trackPageLoadTime()
This method is deprecated because Site Speed reporting is enabled automatically for all users. Please use _setSiteSpeedSampleRate()
to adjust the sampling rate for Site Speed reporting.
Enables Site Speed reports for this page. Insert this method for every page on your site for which you want Site Speed reporting. For more information on the Site Speed reports in Analytics, see the Site Speed article in our Help Center.
Verifying Your Changes
If you see data appearing in the reports, your setup is correct. If you see no data after 24 hours, check your customization to make sure you made no errors. See Troubleshooting the Tracking Code for a list of common tracking code errors. This troubleshooting guide also contains Basic Debugging Steps and more information on debugging.
Be aware that enabling Site Speed tracking for your site results in an extra request made to the Google Analytics servers, separate from the page tracking GIF request made for pageviews. To minimize impact on overall site latency, this request is sent only on a sampling of pageviews to your site. For this reason, you might not always see the site speed GIF request when attempting to debug this feature in Firebug or other tools. This is normal and expected.
Async Snippet (recommended)
_gaq.push(['_setAccount', 'UA-12345-1']);
_gaq.push(['_trackPageview']);
_gaq.push(['_trackPageLoadTime']);
▸
Traditional (ga.js) Snippet
_trackPageview()
_trackPageview(opt_pagePath)
Main logic for GATC (Google Analytic Tracker Code). If linker functionalities are enabled, it attempts to extract cookie values from the URL. Otherwise, it tries to extract cookie values from document.cookie
. It also updates or creates cookies as necessary, then writes them back to the document object. Gathers all the appropriate metrics to send to the UCFE (Urchin Collector Front-end).
Async Snippet (recommended)
_gaq.push(['_setAccount', 'UA-12345-1']);
_gaq.push(['_trackPageview', '/home/landingPage']);
▸
Traditional (ga.js) Snippet
parameters
String opt_pagePath
Optional parameter to indicate the path of the page to track metrics under. When using this option, use a beginning slash (/) to indicate the page path.
GATC Ecommerce Methods
_addItem(transactionId, sku, name, category, price, quantity)
_addTrans(transactionId, affiliation, total, tax, shipping, city, state, country)
_trackTrans()
Method Details
_addItem()
_addItem(transactionId, sku, name, category, price, quantity)
Use this method to track items purchased by visitors to your ecommerce site. This method tracks individual items by their SKU. This means that the
sku
parameter is required. This method then associates the item to the parent transaction object via thetransactionId
argument.Arguments for this method are matched by position, so be sure to supply all parameters, even if some of them have an empty value.
This method performs no additional calculations, such as quantity calculations. Therefore, you should keep in mind the following best practices:
- Calculate quantities with your own software.
- In the same session, duplicate items added (by SKU) do not affect the quantity calculation.
- In the same session, if two items are added where each have the same SKU, the first item information is replaced with the 2nd.
- Ensure that each item in your inventory has a unique SKU.
- If your inventory has different items with the same SKU, and a visitor purchases both of them, you will receive data for only the most recently added.
- Make sure that a parent transaction object is set up for items added.
- If no parent transaction object exists for an added item, the item is attached to an empty transaction object instead.
- If an item is added without a parent transaction object, your reports will show products by SKU that are not associated with any transaction.
- Supply a value for the
name
parameter at all times.- While the
name
parameter is not required, items added to a transaction without aname
parameter do not appear in the product breakdown for a transaction. While you will still see the total revenue for the transaction, you will not be able to see how much revenue a particular item contributed to the transaction total.
- While the
- Calculate quantities with your own software.
- _gaq.push(['_addItem',
'1234', // transaction ID - necessary to associate item with transaction
'DD44', // SKU/code - required
'T-Shirt', // product name - necessary to associate revenue with product
'Olive Medium', // category or variation
'11.99', // unit price - required
'1' // quantity - required
]);
parameters
-
String transactionId
Optional Order ID of the transaction to associate with item.
String sku
Required. Item's SKU code.
String name
Required. Product name. Required to see data in the product detail report.
String category
Optional. Product category.
String price
Required. Product price.
String quantity
Required. Purchase quantity.
_addTrans()
_addTrans(transactionId, affiliation, total, tax, shipping, city, state, country)
- Creates a transaction object with the given values. As with
_addItem()
, this method handles only transaction tracking and provides no additional ecommerce functionality. Therefore, if the transaction is a duplicate of an existing transaction for that session, the old transaction values are over-written with the new transaction values. Arguments for this method are matched by position, so be sure to supply all parameters, even if some of them have an empty value.
- _gaq.push(['_addTrans',
'1234', // transaction ID - required
'Womens Apparel', // affiliation or store name
'28.28', // total - required; Shown as "Revenue" in the
// Transactions report. Does not include Tax and Shipping.
'1.29', // tax
'15.00', // shipping
'San Jose', // city
'California', // state or province
'USA' // country
]);
parameters
-
String transactionId
Required. Internal unique transaction ID number for this transaction.
String affiliation
Optional. Partner or store affiliation (undefined if absent).
String total
Required. Total dollar amount of the transaction. Does not include tax and shipping and should only be considered the "grand total" if you explicity include shipping and tax.
String tax
Optional. Tax amount of the transaction.
String shipping
Optional. Shipping charge for the transaction.
String city
Optional. City to associate with transaction.
String state
Optional. State to associate with transaction.
String country
Optional. Country to associate with transaction.
returns
-
_gat.GA_EComm_.Transactions_
The transaction object that was created or modified.
Note: The optional geographic information that can be included in a transaction object is not used to populate geographic data in Google Analytics reports; however, it can be used in a view filter.
_trackTrans()
_trackTrans()
- Sends both the transaction and item data to the Google Analytics server. This method should be called after
_trackPageview()
, and used in conjunction with the_addItem()
andaddTrans()
methods. It should be called after items and transaction elements have been set up.
- _gaq.push(['_setAccount', 'UA-XXXXX-X']);
_gaq.push(['_trackPageview']);
_gaq.push(['_addTrans',
'1234', // transaction ID - required
'Womens Apparel', // affiliation or store name
'28.28', // total - required
'1.29', // tax
'15.00', // shipping
'San Jose', // city
'California', // state or province
'USA' // country
]);
_gaq.push(['_addItem',
'1234', // transaction ID - necessary to associate item with transaction
'DD44', // SKU/code - required
'T-Shirt', // product name
'Olive Medium', // category or variation
'11.99', // unit price - required
'1' // quantity - required
]);
_gaq.push(['_trackTrans']); -
GATC Event Tracking Methods
_trackEvent(category, action, opt_label, opt_value, opt_noninteraction)
-
Method Details
_trackEvent()
_trackEvent(category, action, opt_label, opt_value, opt_noninteraction)
-
Constructs and sends the event tracking call to the Google Analytics Tracking Code. Use this to track visitor behavior on your website that is not related to a web page visit, such as interaction with a Flash video movie control or any user event that does not trigger a page request. For more information on Event Tracking, see the Event Tracking Guide.
You can use any of the following optional parameters:
opt_label
,opt_value
oropt_noninteraction
. If you want to provide a value only for the second or 3rd optional parameter, you need to pass inundefined
for the preceding optional parameter.parameters
-
String category
The general event category (e.g. "Videos").String action
The action for the event (e.g. "Play").String opt_label
An optional descriptor for the event.Int opt_value
An optional value associated with the event. You can see your event values in the Overview, Categories, and Actions reports, where they are listed by event or aggregated across events, depending upon your report view.Boolean opt_noninteraction
Default value isfalse
. By default, the event hit sent by_trackEvent()
will impact a visitor's bounce rate. By setting this parameter to true, this event hit will not be used in bounce rate calculations.
returns
-
Boolean
whether the event was successfully sent.