• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

revolunet/angular-google-analytics: Google Analytics tracking for your AngularJS ...

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):

revolunet/angular-google-analytics

开源软件地址(OpenSource Url):

https://github.com/revolunet/angular-google-analytics

开源编程语言(OpenSource Language):

JavaScript 100.0%

开源软件介绍(OpenSource Introduction):

angular-google-analytics

Bower Version NPM Version NuGet Master Build Status license

This service lets you integrate google analytics tracker in your AngularJS applications easily.

You can use basic functions, Analytics.trackEvent('video', 'play', 'django.mp4'); or more advanced e-commerce features like product tracking, promo codes, transactions...

Proudly brought to you by @revolunet, @deltaepsilon, @justinsa and contributors

Features

  • highly configurable
  • automatic page tracking
  • event tracking
  • e-commerce (ecommerce.js) support
  • enhanced e-commerce (ec.js) support
  • multiple-domains
  • ga.js (classic) and analytics.js (universal) support
  • cross-domain support
  • multiple tracking objects
  • hybrid mobile application support
  • Chrome extension support
  • offline mode
  • analytics.js advanced debugging support

IMPORTANT! As of version 2.x, methods that were previously marked as deprecated have been removed from this library. The following methods are no longer available: setCookieConfig, getCookieConfig, createAnalyticsScriptTag, and createScriptTag. Each have been replaced with alternative implementations that can be found in this documentation.

Installation and Quick Start

The quick start is designed to give you a simple, working example for the most common usage scenario. There are numerous other ways to configure and use this library as explained in the documentation.

1- Installation:

You can install the module from a package manger of your choice directly from the command line

# Bower
bower install angular-google-analytics

# NPM
npm i angular-google-analytics

# Nuget
nuget install angular-google-analytics

Or alternatively, grab the dist/angular-google-analytics.min.js and include it in your project

In your application, declare the angular-google-analytics module dependency.

<script src="bower_components/angular-google-analytics/dist/angular-google-analytics.js"></script>

2- In your application, declare dependency injection:

var myApp = angular.module('myModule', ['angular-google-analytics']);

3- Set your Google Analytics account and start tracking:

myApp.config(['AnalyticsProvider', function (AnalyticsProvider) {
   // Add configuration code as desired
   AnalyticsProvider.setAccount('UU-XXXXXXX-X');  //UU-XXXXXXX-X should be your tracking code
}]).run(['Analytics', function(Analytics) { }]);

Congratulations! angular-google-analytics is ready and Google Analytics will track your page views once the application is run

Configure Service

app.config(function (AnalyticsProvider) {
  // Add configuration code as desired - see below
});

Configuration Method Chaining

  // All configuration methods return the provider object and can be chained to reduce typing.
  // For example:
  AnalyticsProvider
    .logAllCalls(true)
    .startOffline(true)
    .useECommerce(true, true);

Use Classic Analytics

// Use ga.js (classic) instead of analytics.js (universal)
// By default, universal analytics is used, unless this is called with a falsey value.
AnalyticsProvider.useAnalytics(false);

Set Google Analytics Accounts (Required)

// Set a single account
AnalyticsProvider.setAccount('UA-XXXXX-xx');

Note: the single account syntax is internally represented as an unnamed account object that will have all properties defined to defaults, except for name.

// Set multiple accounts
// Universal Analytics only
AnalyticsProvider.setAccount([
   { tracker: 'UA-12345-12', name: "tracker1" },
   { tracker: 'UA-12345-34', name: "tracker2" }
]);

Note: the above account objects will have all properties defined to defaults that are not defined.

// Set a single account with all properties defined
// Universal Analytics only
AnalyticsProvider.setAccount({
  tracker: 'UA-12345-12',
  name: "tracker1",
  fields: {
    cookieDomain: 'foo.example.com',
    cookieName: 'myNewName',
    cookieExpires: 20000
    // See: [Analytics Field Reference](https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference) for a list of all fields.
  },
  crossDomainLinker: true,
  crossLinkDomains: ['domain-1.com', 'domain-2.com'],
  displayFeatures: true,
  enhancedLinkAttribution: true,
  select: function (args) {
    // This function is used to qualify or disqualify an account object to be run with commands.
    // If the function does not exist, is not a function, or returns true then the account object will qualify.
    // If the function exists and returns false then the account object will be disqualified.
    // The 'args' parameter is the set of arguments (which contains the command name) that will be sent to Universal Analytics.
    return true;
  },
  set: {
    forceSSL: true
    // This is any set of `set` commands to make for the account immediately after the `create` command for the account.
    // The property key is the command and the property value is passed in as the argument, _e.g._, `ga('set', 'forceSSL', true)`.
    // Order of commands is not guaranteed as it is dependent on the implementation of the `for (property in object)` iterator.
  },
  trackEvent: true,
  trackEcommerce: true
});

Note: the above properties are referenced and discussed in proceeding sections.

Use Display Features

  // Use display features module
  AnalyticsProvider.useDisplayFeatures(true);

If set to a truthy value then the display features module is loaded with Google Analytics.

In the case of universal analytics, this value will be used as the default for any tracker that does not have the displayFeatures property defined. All trackers with displayFeatures: true will be registered for display features.

Use Enhanced Link Attribution

  // Enable enhanced link attribution module
  AnalyticsProvider.useEnhancedLinkAttribution(true);

If set to a truthy value then the enhanced link attribution module is loaded with Google Analytics.

In the case of universal analytics, this value will be used as the default for any tracker that does not have the enhancedLinkAttribution property defined. All trackers with enhancedLinkAttribution: true will be registered for enhanced link attribution.

Use Cross Domain Linking

  // Use cross domain linking and set cross-linked domains
  AnalyticsProvider.useCrossDomainLinker(true);
  AnalyticsProvider.setCrossLinkDomains(['domain-1.com', 'domain-2.com']);

If set to a truthy value then the cross-linked domains are registered with Google Analytics.

In the case of universal analytics, these values will be used as the default for any tracker that does not have the crossDomainLinker and crossLinkDomains properties defined. All trackers with crossDomainLinker: true will register the cross-linked domains.

Track Events

This property is defined for universal analytics account objects only and is false by default.

If trackEvent: true for an account object then all trackEvent calls will be supported for that account object.

Set trackEvent: false for an account object that is not tracking events.

Track E-Commerce

This property is defined for universal analytics account objects only. This property defaults to true if e-commerce is enabled (either classic or enhanced) and false otherwise.

If trackEcommerce: true for an account object then all e-commerce calls will be supported for that account object.

Set trackEcommerce: false for an account object that is not tracking e-commerce.

Enable E-Commerce

  // Enable e-commerce module (ecommerce.js)
  AnalyticsProvider.useECommerce(true, false);

  // Enable enhanced e-commerce module (ec.js)
  // Universal Analytics only
  AnalyticsProvider.useECommerce(true, true);

  // Set Currency
  // Default is 'USD'. Use ISO currency codes.
  AnalyticsProvider.setCurrency('CDN');

Note: When enhanced e-commerce is enabled, the legacy e-commerce module is disabled and unsupported. This is a requirement of Google Analytics.

Set Route Tracking Behaviors

Note: In order to set route tracking behavior in the $routeProvider you need the ngRoute module in your application. Please refer to the official angular ngRoute documentation on how to install and use this service.

  // Track all routes (default is true).
  AnalyticsProvider.trackPages(true);

  // Track all URL query params (default is false).
  AnalyticsProvider.trackUrlParams(true);

  // Ignore first page view (default is false).
  // Helpful when using hashes and whenever your bounce rate looks obscenely low.
  AnalyticsProvider.ignoreFirstPageLoad(true);

  // URL prefix (default is empty).
  // Helpful when the app doesn't run in the root directory.
  AnalyticsProvider.trackPrefix('my-application');

  // Change the default page event name.
  // Helpful when using ui-router, which fires $stateChangeSuccess instead of $routeChangeSuccess.
  AnalyticsProvider.setPageEvent('$stateChangeSuccess');

  // RegEx to scrub location before sending to analytics.
  // Internally replaces all matching segments with an empty string.
  AnalyticsProvider.setRemoveRegExp(/\/\d+?$/);

  // Activate reading custom tracking urls from $routeProvider config (default is false)
  // This is more flexible than using RegExp and easier to maintain for multiple parameters.
  // It also reduces tracked pages to routes (only those with a templateUrl) defined in the
  // $routeProvider and therefore reduces bounce rate created by redirects.
  // NOTE: The following option requires the ngRoute module
  AnalyticsProvider.readFromRoute(true);
  // Add custom routes to the $routeProvider like this. You can also exclude certain routes from tracking by
  // adding 'doNotTrack' property
  $routeProvider
    .when('/sessions', {
      templateUrl: 'list.html',
      controller: 'ListController'
    })
    .when('/session/:id',{
      templateUrl : 'master.html',
      controller: 'MasterController',
      pageTrack: '/session'  // angular-google-analytics extension
    })
    .when('/member/:sessionId/:memberId', {
      templateUrl : 'member.html',
      controller: 'CardController',
      pageTrack: '/member',  // angular-google-analytics extension
    })
    .otherwise({
      templateUrl: '404.html',
      doNotTrack: true       // angular-google-analytics extension
    });

Set Domain Name

  // Set the domain name
  AnalyticsProvider.setDomainName('XXX');

Note: Use the string 'none' for testing on localhost.

Enable Experiment (universal analytics only)

  // Enable analytics.js experiments
  AnalyticsProvider.setExperimentId('12345');

Note: only a single experiment can be defined.

Support Hybrid Mobile Applications (universal analytics only)

  // Set hybrid mobile application support
  AnalyticsProvider.setHybridMobileSupport(true);

If set to a truthy value then each account object will disable protocol checking and all injected scripts will use the HTTPS protocol.

Delay Script Tag Insertion and Tracker Setup

  // Must manually call registerScriptTags method in order to insert the Google Analytics scripts on the page.
  //   Analytics.registerScriptTags();
  // Must manually call registerTrackers method in order to setup the trackers with Google Analytics.
  //   Analytics.registerTrackers();
  // Helpful when needing to do advanced configuration or user opt-out and wanting explicit control
  // over when the Google Analytics scripts get injected or tracker setup happens.
  AnalyticsProvider.delayScriptTag(true);

Offline Mode

  // Start in offline mode if set to true. This also calls delayScriptTag(true) since the script cannot be
  // fetched if offline and must be manually called when the application goes online.
  AnalyticsProvider.startOffline(true);

Disable Analytics / User Opt-out

  // Disable analytics data gathering via the user opt-out feature in Google Analytics. More information on this
  // is available here: https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced#optout.
  AnalyticsProvider.disableAnalytics(true);

Note: Using this configuration option requires that you already know the user wants to opt-out before the analytics script is injected on the page. This is somewhat unlikely for most use cases given the nature of a single page application. This module provides a better alternative with Offline mode since you can effectively opt the user out of tracking by enabling offline mode at any time during execution.

Service Logging

  // Log all outbound calls to an in-memory array accessible via ```Analytics.log``` (default is false).
  // This is useful for troubleshooting and seeing the order of calls with parameters.
  AnalyticsProvider.logAllCalls(true);

Test Mode

  // This method is designed specifically for unit testing and entering test mode cannot be changed after
  // being called. Test mode skips the insertion of the Google Analytics script tags (both classic and universal)
  // and ensures there is a $window.ga() method available for calling by unit tests. This corrects transient
  // errors that were seen during unit tests due to the operation of the Google Analytics scripts.
  AnalyticsProvider.enterTestMode();

Debug Mode

  // Calling this method will enable debugging mode for Universal Analytics. Supplying a truthy value for the
  // optional parameter will further enable trace debugging for Universal Analytics. More information on this
  // is available here: https://developers.google.com/analytics/devguides/collection/analyticsjs/debugging.
  AnalyticsProvider.enterDebugMode(Boolean);

Anonymize IP

AnalyticsProvider.setAccount({
  tracker: 'UA-12345-12',
  set: {
    anonymizeIp: true
  }
}

Using the Analytics Service

IMPORTANT! Due to how Google Analytics works, it is important to remember that you must always call Analytics.pageView(); when you want to push setting changes and function calls to Google Analytics.

Automatic Page View Tracking

If you are relying on automatic page tracking, you need to inject Analytics at least once in your application.

  // As an example, add the service to the run call:
  app.run(function(Analytics) {});

Declaring a Controller

  // As an example, a simple controller to make calls from:
  app.controller('SampleController', function (Analytics) {
    // Add calls as desired - see below
  });

热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap