Page Tracking

本文详细介绍如何使用analytics.js库进行各种网站活动的跟踪测量,包括页面浏览、虚拟页面视图、事件、社交互动、屏幕视图、用户计时及异常跟踪等,提供了丰富的代码示例和最佳实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Page tracking allows you to measure the number of views you had for a particular page on your website. Pages often correspond to an entire HTML document, but they can also represent dynamically loaded content; this is known as "virtual pageviews".

This guide explains how to implement page tracking with analytics.js.

Overview

The JavaScript tracking snippet includes a command to create a tracker object and then a command to send a pageview to Google Analytics. When the tracker gets created, several of the fields get set based on the browsing context. The title field is set to the value of document.title, and the location field gets set to the value of document.location, ignoring the anchor portion of the URL.

Note: if the anchor portion of the URL contains campaign parameters, those parameters get kept in the anchor and sent to Google Analytics for processing (unless the allowAnchor field is set to false).

When the send command is executed, the title and location fields stored on the tracker get sent, and Google Analytics uses those values to show you which pages your users visited.

The default tracker does not set the page field, but if you set it manually, that value gets used as the page path in reports, overriding the location field's value.

Implementation

Pageview hits can be sent using the send command and specifying a hitType of pageview. The send command has the following signature for the pageview hit type:

 

ga('send', 'pageview', [page], [fieldsObject]);

Pageview fields

The following table summarizes the primary fields relevant to tracking pageviews. For more details (and some additional fields) see the content information section of the field reference.

Field NameValue TypeRequiredDescription
titletextnoThe title of the page (e.g. homepage)
locationtextno *URL of the page being tracked.
pagetextno *The path portion of a URL. This value should start with a slash (/) character.

*  though neither the page field nor the location field is required, one of them must be present or the hit will be invalid.

Examples:

The following command sends a pageview hit to Google Analytics and includes the path of the current page.

 

ga('send', 'pageview', location.pathname);

Note that as with all send commands, the fields passed in the convenience parameters may also be specified in the fieldsObject. The above command could be rewritten as:

 

ga('send', {
  hitType: 'pageview',
  page: location.pathname
});

For more details, examples, and best practices for sending hits, see the Sending Data to Google Analytics guide. For more details on the calling signature of the send command, see the command queue reference.

Modifying page URLs

In some cases the URL you want to send to Google Analytics is different from the URL that appears in the address bar of the user's browser. For example, consider a site with a few pages where users can log in and view/edit their personal information. If this site has separate pages for personal information, account information, and notification settings, the URLs for these pages might look something like this:

  • /user/USER_ID/profile
  • /user/USER_ID/account
  • /user/USER_ID/notifications

If you want to know, in total, how many people visit each of these pages, including a unique user ID value in the URLs will make that much more difficult.

To solve this problem you can specify a page value with the user ID removed:

 

// Checks to see if the current user's userID is
// found in the URL, if it is, remove it.
// (Note, this assume the user ID is stored
// in a variable called `userID`)

if (document.location.pathname.indexOf('user/' + userID) > -1) {
  var page = document.location.pathname.replace('user/' + userID, 'user');
  ga('send', 'pageview', page);
}

This will send the following page values for all users:

  • /user/profile
  • /user/account
  • /user/notifications

If the current page is sending other hits (like events), you'll want to make sure every hit gets sent with the correct URL. In such cases, you should update the page field on the tracker instead of passing it in the send command.

Setting it on the tracker will ensure the new page value gets used for all subsequent hits:

 

if (document.location.pathname.indexOf('user/' + userID) > -1) {
  var page = document.location.pathname.replace('user/' + userID, 'user');

  // Sets the page value on the tracker.
  ga('set', 'page', page);

  // Sending the pageview no longer requires passing the page
  // value since it's now stored on the tracker object.
  ga('send', 'pageview');
}

Tracking virtual pageviews

Many websites today load content dynamically via AJAX without requiring a full page load for each "page". Such sites are commonly referred to as Single Page Applications (SPAs).

If your website loads page content dynamically and updates the document's URL, you'll usually want to send additional pageviews to track these "virtual pageviews". For full implementation details, see the guide on Single Page Application Tracking with analytics.js.

Single Page Application Tracking

This guide describes how to use analytics.js to track pages on sites whose content is loaded dynamically without traditional full page loads.

Overview

Single Page Application (SPA) is a web application or website that loads all of the resources required to navigate throughout the site on the first page load. As the user clicks links and interacts with the page, subsequent content is loaded dynamically. The application will often update the URL in the address bar to emulate traditional page navigation, but another full page request is never made.

The default JavaScript tracking snippet works well with traditional websites because the snippet code is run every single time the users load a new page. However, for a single page application where the site loads new page content dynamically rather than as full page loads, the analytics.js snippet code only runs once. This means subsequent (virtual) pageviews must be tracked manually as new content is loaded.

Note: Developers creating Single Page Applications can use autotrack, which includes a urlChangeTracker plugin that handles all of the important considerations listed in this guide for you. See the autotrack documentation for usage and installation instructions.

Tracking virtual pageviews

When your application loads content dynamically and updates the URL in the address bar, the data stored on your tracker should be updated as well.

To update the tracker, use the set command and supply the new page value:

 

ga('set', 'page', '/new-page.html');

After you've set the new page value, all subsequents hits sent will use that new value. To record a pageview, send a pageview hit immediately after updating the tracker.

 

ga('set', 'page', '/new-page.html');
ga('send', 'pageview');

While technically the send command for pageview hits accepts an optional page field as the third parameter, passing the page field that way is not recommended when tracking single page applications. This is because fields passed via the send command are not set on the tracker—they apply to the current hit only. Not updating the tracker will cause problems if your application sends any non-pageview hits (e.g. events or social interactions), as those hits will be associated with whatever page value the tracker had when it was created.

Handling multiple URLs for the same resource

Some SPAs only update the hash portion of the URL when loading content dynamically. This practice can lead to situations where many different page paths point to the same resource. In such cases, it's usually best to choose a canonical URL and only ever send that page value to Google Analytics.

For example, consider a website whose "About Us" page can be reached via any of the following URLs:

  • /about.html
  • /#about.html
  • /home.html#about.html

To avoid duplication in your reports, it's best to track all of these pageviews as /about.html.

Important considerations

Do not update the document referrer

When you create a tracker object using the create command, the value of document.referrer is stored on the tracker's referrer field. In the context of a single page application that doesn't use full page loads, the referrer field will always stay the same.

Despite this, it is not necessary to update the referrer field manually prior to sending pageview hits. Google Analytics is able to automatically determine the correct navigation path.

Do not update the document location

In the same way that the tracker uses document.referrer for the referrer field, it uses document.location for the location field, which may contain campaign data or other meta data in the form of query parameters appended to the end of the URL.

Updating any of the campaign fields or other meta data that Google Analytics is checking for may cause the current session to end and a new session to begin. To avoid this problem, do not update the location field when tracking virtual pageviews in a single page application. Use the page field instead.

Note: If you send a hit that includes both the location and page fields and the path values are different, Google Analytics will use the value specified for the page field.

Do not create new trackers

Do not create new trackers in a single page app in an attempt to mimic what the JavaScript tracking snippet does for traditional websites. Doing so runs the risk of sending an incorrect referrer as well as incorrect campaign data as described above.

Event Measurement

This guide explains how to measure events with analytics.js.

Overview

Events are user interactions with content that can be measured independently from a web page or a screen load. Downloads, mobile ad clicks, gadgets, Flash elements, AJAX embedded elements, and video plays are all examples of actions you might want to measure as Events.

If you're unfamiliar with events in Google Analytics you should first read the article About Events in the Analytics Help Center.

Implementation

Event hits can be sent using the send command and specifying a hitType of event. The send command has the following signature for the event hit type:

 

ga('send', 'event', [eventCategory], [eventAction], [eventLabel], [eventValue], [fieldsObject]);

Event fields

The following table summarizes the event fields:

Field NameValue TypeRequiredDescription
eventCategorytextyesTypically the object that was interacted with (e.g. 'Video')
eventActiontextyesThe type of interaction (e.g. 'play')
eventLabeltextnoUseful for categorizing events (e.g. 'Fall Campaign')
eventValueintegernoA numeric value associated with the event (e.g. 42)

For a more in-depth description of each of these fields, see Anatomy of an Event in the Analytics Help Center.

Examples:

The following command sends an event to Google Analytics indicating that the fall campaign promotional video was played:

 

ga('send', 'event', 'Videos', 'play', 'Fall Campaign');

Note that as with all send commands, the fields passed in the convenience parameters may also be specified in the fieldsObject. The above command could be rewritten as:

 

ga('send', {
  hitType: 'event',
  eventCategory: 'Videos',
  eventAction: 'play',
  eventLabel: 'Fall Campaign'
});

For more details, examples, and best practices for sending hits, see the Sending Data to Google Analytics guide. For more details on the calling signature of the send command, see the command queue reference.

When a user clicks a link that points to another page on your site, that page typically sends a pageview hit as the user arrives. Because there's a series of pageviews, Google Analytics can figure out on the back end where the user navigated to (and from). But if a user clicks a link or submits a form to an external domain, that action is not captured unless you specifically tell Google Analytics what happened.

Outbound link and form event measurement can be accomplished by sending events and specifying the destination URL in one of the event fields. The following event handler function can be used to send outbound link click events to Google Analytics:

 

function handleOutboundLinkClicks(event) {
  ga('send', 'event', {
    eventCategory: 'Outbound Link',
    eventAction: 'click',
    eventLabel: event.target.href
  });
}

Measuring outbound links and forms can be tricky because most browsers will stop executing JavaScript on the current page once a new page starts to load. One solution to this problem is to set the transport field to beacon:

 

function handleOutboundLinkClicks(event) {
  ga('send', 'event', {
    eventCategory: 'Outbound Link',
    eventAction: 'click',
    eventLabel: event.target.href,
    transport: 'beacon'
  });
}

For browsers that don't support the beacon transport method, you have to postpone navigating to the next page until the event has finished sending. The Knowing when a hit has been sent section of the guide on Sending data to Google Analytics explains how to do this in detail.

Note: Developers wanting to measure outbound links and forms can use autotrack, which includes the outboundLinkTrackerand outboundFormTracker plugins that handle these complexities for you. See the autotrack documentation for usage and installation instructions.

Non-interaction events

In some cases you might want to send an event as a non-interaction event. To do this, specify the nonInteraction field as true in the fieldsObject of the send command:

 

ga('send', 'event', 'Videos', 'play', 'Fall Campaign', {
  nonInteraction: true
});

For more information on non-interaction hits and when to use them, read about non-interaction events in the Analytics Help Center

Social Interactions

This guide describes how to measure social interactions using analytics.js.

Overview

You can use social interaction analytics to measure the number of times users click on social buttons embedded in webpages. For example, you might measure a Facebook "Like" or a Twitter "Tweet".

While event tracking measures general user-interactions very well, Social Analytics provides a consistent framework for recording social interactions. This in turn provides a consistent set of reports to compare social network interactions across multiple networks.

If you're unfamiliar with social interactions in Google Analytics, or you're not sure what values to use for the social network, action, or target, you should first read the article About Social plugins and interactions in the Analytics Help Center.

Implementation

Social interaction hits can be sent using the send command and specifying a hitType of social. The send command has the following signature for the social hit type:

 

ga('send', 'social', [socialNetwork], [socialAction], [socialTarget], [fieldsObject]);

Social interaction fields

The following table summarizes the social interaction fields:

Field NameValue TypeRequiredDescription
socialNetworktextyesThe network on which the action occurs (e.g. Facebook, Twitter)
socialActiontextyesThe type of action that happens (e.g. Like, Send, Tweet).
socialTargettextyesSpecifies the target of a social interaction. This value is typically a URL but can be any text. (e.g. http://mycoolpage.com)

For a more in-depth description of each of these fields, see Data collection in the Analytics Help Center.

Examples

The following command sends a social interaction hit to Google Analytics indicating that a Facebook like button was clicked for the site http://myownpersonaldomain.com:

 

ga('send', 'social', 'Facebook', 'like', 'http://myownpersonaldomain.com');

Note that as with all send commands, the fields passed in the convenience parameters may also be specified in the fieldsObject. The above command could be rewritten as:

 

ga('send', {
  hitType: 'social',
  socialNetwork: 'Facebook',
  socialAction: 'like',
  socialTarget: 'http://myownpersonaldomain.com'
});

For more details, examples, and best practices for sending hits, see the Sending Data to Google Analytics guide. For more details on the calling signature of the send command, see the command queue reference.

Facebook

If you use the official Facebook Like buttons and subscribe to the edge.create event, when a Like action happens, you are notified.

 

FB.Event.subscribe('edge.create', function(url) {
  ga('send', 'social', 'facebook', 'like', url);
});

For more details, refer to the Facebook JavaScript SDK.

Note: Developers using the official Facebook or Twitter widgets can use autotrack, which includes a socialTracker plugin that automatically tracks social interactions for the "Like", "Tweet", and "Follow" buttons. See the autotrack documentation for usage and installation instructions.

Google+

By default, Google Analytics provides integrated reporting for the +1 Button. This means if you have implemented analytics.js and a +1 Button on the same page, all +1 interactions will be automatically reported as social interactions via each of the trackers on the page. For more information on +1 Analytics, including troubleshooting tips, see About Social Analytics in the Help Center.

App / Screen Measurement

This guide describes how to set up screen event measurement with analytics.js

Overview

Screens in Google Analytics represent content users are viewing within an app. The equivalent concept for a website is pages. Measuring screen views allows you to see which content is being viewed most by your users, and how are they are navigating between different pieces of content.

Implementation

Screen hits can be sent using the send command and specifying a hitType of screenview. The send command has the following signature for the screenview hit type:

 

ga('send', 'screenview', [fieldsObject]);

Screen fields

Field NameValue TypeRequiredDescription
screenNametextyesThe name of the screen.

Screen data is typically sent to Google Analytics views of type "app" (rather than "web"), which means in addition to sending the screenName, you must also send at least the appName field.

The following table lists the app fields that can be sent to app views.

Field NameValue TypeRequiredDescription
appNametextyesThe name of the application.
appIdtextnoThe Id of the application.
appVersiontextnoThe application version.
appInstallerIdtextnoThe Id of the application installer.

For more details on the distinction between web and app views in Google Analytics, refer to the Difference between web and app views article in the Analytics Help Center.

Examples

The following command sends a screenview hit to Google Analytics for an app named "myAppName" and the screen "Home":

 

ga('send', 'screenview', {
  'appName': 'myAppName',
  'screenName': 'Home'
});

Since the appName field must be sent with all app hits, it's often best to set that field with the set command:

 

ga('create', 'GA_MEASUREMENT_ID', 'auto');
ga('set', 'appName', 'myAppName');

// The `appName` field is now set, so
// screenview hits don't need to include it.
ga('send', 'screenview', {screenName: 'Home'});

For more details, examples, and best practices for sending hits, see the Sending Data to Google Analytics guide. For more details on the calling signature of the send command, see the command queue reference.

Using filters for app-only or web-only views

If you send web and app data for the same property (UA-XXXXX-Y), Google Analytics will display both sets of data in views for that property. This allows for combined app and web views.

If you want to send app and web data for the same property but maintain a separate app and/or web view you can create Filters. For example, you can have a combined view (default), a web view, and an app view.

App View Filter

Create a Custom Filter to Include only app data by setting Application? to yes.

The Google Analytics create filter form. The filter name field is set to 'App View', 'Custom Filter' type is selected, 'Include' is selected, Filter Field dropdown is set to 'Application?', Filter Pattern is set to 'yes', and Case Sensitive is set to 'No'.

Figure 1: Filter settings for an App View.

Web view filter

Create a Custom Filter to Include only web data by setting Application? to no.

The Google Analytics create filter form. The filter name field is set to 'Web View', 'Custom Filter' type is selected, 'Include' is selected, Filter Field dropdown is set to 'Application?', Filter Pattern is set to 'no', and Case Sensitive is set to 'No'.

Figure 2: Filter settings for a Web View.

User Timings

This guide describes how to measure periods of time using analytics.js.

Overview

Studies have shown that reducing page load time improves the overall user experience of a site. Google Analytics has a number of powerful reports that automatically measure and report on page load times. However, it is also possible to track custom timing information to measure performance specific to your site.

User timings allow developers to measure periods of time using the analytics.js library. This is particularly useful for developers to measure the latency, or time spent, making AJAX requests and loading web resources.

Implementation

User timings hits can be sent using the send command and specifying a hitType of timing. The send command has the following signature for the timing hit type:

 

ga('send', 'timing', [timingCategory], [timingVar], [timingValue], [timingLabel], [fieldsObject]);

User timings fields

The following table summarizes the user timings fields:

Field NameValue TypeRequiredDescription
timingCategorytextyesA string for categorizing all user timing variables into logical groups (e.g. 'JS Dependencies').
timingVartextyesA string to identify the variable being recorded (e.g. 'load').
timingValueintegeryesThe number of milliseconds in elapsed time to report to Google Analytics (e.g. 20).
timingLabeltextnoA string that can be used to add flexibility in visualizing user timings in the reports (e.g. 'Google CDN').

Examples:

The following command sends a user timing hit to Google Analytics indicating that it took 3549 milliseconds for the current web page to load all its external JavaScript dependencies:

 

ga('send', 'timing', 'JS Dependencies', 'load', 3549);

Note that as with all send commands, the fields passed in the convenience parameters may also be specified in the fieldsObject. The above command could be rewritten as:

 

ga('send', {
  hitType: 'timing',
  timingCategory: 'JS Dependencies',
  timingVar: 'load',
  timingValue: 3549
});

For more details, examples, and best practices for sending hits, see the Sending Data to Google Analytics guide. For more details on the calling signature of the send command, see the command queue reference.

Measuring time

When sending user timing data, you specify the amount of milliseconds spent in the timingValue parameter. It’s up to you to write code to capture this period of time.

The easiest way to do this is to create a timestamp at the beginning of a period of time and create another timestamp at the end of the period. Then you can take the difference between both timestamps to get time spent.

Most modern browsers support the Navigation Timing API, which includes methods on the window.performance object for measuring the performance of web pages through high-resolution time data.

The following example uses the performance.now() method, which returns the amount of time that has elapsed since the page first started loading:

 

// Feature detects Navigation Timing API support.
if (window.performance) {
  // Gets the number of milliseconds since page load
  // (and rounds the result since the value must be an integer).
  var timeSincePageLoad = Math.round(performance.now());

  // Sends the timing hit to Google Analytics.
  ga('send', 'timing', 'JS Dependencies', 'load', timeSincePageLoad);
}

Sampling considerations

Google Analytics will sample timing hits during processing in order to ensure an equitable distribution of system resources for this feature.

The rate at which timing hits are sampled is determined by the total number of pageview hits received during the previous day for the property. The following table outlines how the timing sampling rate is determined:

Total pageview hit count (previous day)Maximum number of timing hits that will be processed
0 - 1,000100
1,000 - 100,00010% of total pageview hit count
100,000 - 1,000,00010,000
1,000,000+1% of total pageview hit count

Limiting the number of hits sent

To avoid sending Google Analytics hits that will not be processed, analytics.js allows you to control the percentage of hits that are sent via the sampleRate and siteSpeedSampleRate configuration options. By default these fields are set to 100% and 1%, respectively. You can adjust these values to more closely approximate the number of timing hits Google Analytics will process based on your average daily pageview counts.

Exception Tracking

This guide describes how to send exceptions using analytics.js. Exception tracking allows you to measure the number and type of crashes or errors that occur on your property.

Implementation

Exception hits can be sent using the send command and specifying a hitType of exception. The send command has the following signature for the exception hit type:

 

ga('send', 'exception', [fieldsObject]);

Exception fields

The following table summarizes the exception fields:

Field NameValue TypeRequiredDescription
exDescriptiontextnoA description of the exception.
exFatalbooleannotrue if the exception was fatal.

Example

The following command wraps some logic that may fail in a try/catch block. If there's an error, it sends an exception hit to Google Analytics:

 

try {
  // Runs code that may or may not work.
  window.possiblyUndefinedFunction();
} catch(err) {
  ga('send', 'exception', {
    'exDescription': err.message,
    'exFatal': false
  });
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值