Coder Social home page Coder Social logo

angular-google-analytics's 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
  });

Accessing Configuration Settings

The following configuration settings are intended to be immutable. While the values can be changed in this list by the user, this will not impact the behavior of the service as these values are not referenced internally; exceptions are noted below but are not intended to be utilized in such a way by the user. No guarantee will be made for future versions of this service supporting any functionality beyond reading values from this list.

  // This is a mutable array. Changes to this list will impact service behaviors.
  Analytics.configuration.accounts;

  // If `true` then universal analytics is being used.
  // If `false` then classic analytics is being used.
  Analytics.configuration.universalAnalytics;

  Analytics.configuration.crossDomainLinker;
  Analytics.configuration.crossLinkDomains;
  Analytics.configuration.currency;
  Analytics.configuration.debugMode;

  Analytics.configuration.delayScriptTag;
  Analytics.configuration.disableAnalytics;
  Analytics.configuration.displayFeatures;
  Analytics.configuration.domainName;

  // ecommerce and enhancedEcommerce are mutually exclusive; either both will be false or one will be true.
  Analytics.configuration.ecommerce;
  Analytics.configuration.enhancedEcommerce;

  Analytics.configuration.enhancedLinkAttribution;
  Analytics.configuration.experimentId;
  Analytics.configuration.ignoreFirstPageLoad;
  Analytics.configuration.logAllCalls;
  Analytics.configuration.pageEvent;
  Analytics.configuration.removeRegExp;
  Analytics.configuration.traceDebuggingMode;
  Analytics.configuration.trackPrefix;
  Analytics.configuration.trackRoutes;
  Analytics.configuration.trackUrlParams;

Get URL

  // Returns the current URL that would be sent if a `trackPage` call was made.
  // The returned value takes into account all configuration settings that modify the URL.
  Analytics.getUrl();

Manual Script Tag Injection and Tracker Setup

If delayScriptTag(true) was set during configuration then manual script tag injection and tracker setup is required. Otherwise, the script tag and trackers will be automatically injected and configured when the service is instantiated.

  // Manually create either classic analytics (ga.js) or universal analytics (analytics.js) script tags
  Analytics.registerScriptTags();

  // Manually setup the tracker object(s)
  Analytics.registerTrackers();

Advanced Settings / Custom Dimensions

The set call allows for advanced configuration and definitions in universal analytics only. This is a no-op when using classic analytics.

  // Set the User Id
  Analytics.set('&uid', 1234);

  // Register a custom dimension for the default, unnamed account object
  // e.g., ga('set', 'dimension1', 'Paid');
  Analytics.set('dimension1', 'Paid');

  // Register a custom dimenstion for a named account object
  // e.g., ga('accountName.set', 'dimension2', 'Paid');
  Analytics.set('dimension2', 'Paid', 'accountName');

Page Tracking

  // Create a new pageview event
  Analytics.trackPage('/video/detail/XXX');

  // Create a new pageview event with page title
  Analytics.trackPage('/video/detail/XXX', 'Video XXX');

  // Create a new pageview event with page title, custom dimension, and custom metric
  // Universal Analytics only
  Analytics.trackPage('/video/detail/XXX', 'Video XXX', { dimension15: 'My Custom Dimension', metric18: 8000 });

Event Tracking

  // Create a new tracking event
  Analytics.trackEvent('video', 'play', 'django.mp4');

  // Create a new tracking event with a value
  Analytics.trackEvent('video', 'play', 'django.mp4', 4);

  // Create a new tracking event with a value and non-interaction flag
  Analytics.trackEvent('video', 'play', 'django.mp4', 4, true);

  // Create a new tracking event with a value, non-interaction flag, custom dimension, and custom metric
  // Universal Analytics only
  Analytics.trackEvent('video', 'play', 'django.mp4', 4, true, { dimension15: 'My Custom Dimension', metric18: 8000 });
  
  // Track an event that is an outbound transport request
  Analytics.trackEvent(
    'video',
    'play',
    'django.mp4',
    4,
    true,
    {
      dimension15: 'My Custom Dimension',
      metric18: 8000,
      transport: 'beacon',
      hitCallback: function () {
        document.location = 'http://google.com';
      }
    }
  );

Track User Timings

The trackTimings call is available for universal analytics only. This is a no-op when using classic analytics.

  Analytics.trackTimings(timingCategory, timingVar, timingValue, timingLabel);

  // example:
  var endTime = new Date().getTime(),
      timeSpent = endTime - startTime;
  Analytics.trackTimings('Time to Checkout', 'User Timings', timeSpent);

Classic E-Commerce (ecommerce.js)

Classic e-commerce and enhanced e-commerce are mutually exclusive.

  // Create transaction
  Analytics.addTrans('1', '', '2.42', '0.42', '0', 'Amsterdam', '', 'Netherlands', 'EUR');

  // Add items to transaction
  Analytics.addItem('1', 'sku-1', 'Test product 1', 'Testing', '1', '1');
  Analytics.addItem('1', 'sku-2', 'Test product 2', 'Testing', '1', '1');

  // Complete transaction
  Analytics.trackTrans();

  // Clear transaction
  Analytics.clearTrans();

Enhanced E-Commerce (ec.js)

Enhanced e-commerce is only available for universal analytics. Enhanced e-commerce and classic e-commerce are mutually exclusive.

Product Impression Tracking

  Analytics.addImpression(productId, name, list, brand, category, variant, position, price);
  Analytics.pageView();

  // example:
  Analytics.addImpression('sku-1', 'Test Product 1', 'Category List', 'Brand 1', 'Category-1', 'variant-1', '1', '24990');
  Analytics.addImpression('sku-2', 'Test Product 2', 'Category List', 'Brand 2', 'Category-1', 'variant-3', '2', '2499');
  Analytics.pageView();

Product Click Tracking

  Analytics.addProduct(productId, name, category, brand, variant, price, quantity, coupon, position, custom);
  Analytics.productClick(listName);

  // example:
  Analytics.addProduct('sku-2', 'Test Product 2', 'Category-1', 'Brand 2', 'variant-3', '2499', '1', 'FLAT10', '1');
  Analytics.productClick('Search Result');

  // example with custom dimension and metric:
  Analytics.addProduct('sku-2', 'Test Product 2', 'Category-1', 'Brand 2', 'variant-3', '2499', '1', 'FLAT10', '1', { dimension4: 'strong', metric2: 5 });
  Analytics.productClick('Search Result');

Product Detail Tracking

  Analytics.addProduct(productId, name, category, brand, variant, price, quantity, coupon, position);
  Analytics.trackDetail();

  // example:
  Analytics.addProduct('sku-2', 'Test Product 2', 'Category-1', 'Brand 2', 'variant-3', '2499', '1', 'FLAT10', '1');
  Analytics.trackDetail();

Add to Cart Tracking

  Analytics.addProduct(productId, name, category, brand, variant, price, quantity, coupon, position);
  Analytics.trackCart('add', listName); // listname is optional

  // example:
  Analytics.addProduct('sku-2', 'Test Product 2', 'Category-1', 'Brand 2', 'variant-3', '2499', '1', 'FLAT10', '1');
  Analytics.addProduct('sku-2', 'Test Product 2', 'Category-1', 'Brand 2', 'variant-3', '2499', '1', 'FLAT10', '1');
  Analytics.trackCart('add', 'Search Result');

Remove from Cart Tracking

  Analytics.addProduct(productId, name, category, brand, variant, price, quantity, coupon, position);
  Analytics.trackCart('remove', listName); // listname is optional

  // example:
  Analytics.addProduct('sku-2', 'Test Product 2', 'Category-1', 'Brand 2', 'variant-3', '2499', '1', 'FLAT10', '1');
  Analytics.addProduct('sku-2', 'Test Product 2', 'Category-1', 'Brand 2', 'variant-3', '2499', '1', 'FLAT10', '1');
  Analytics.trackCart('remove', 'Search Result');

Checkout Tracking

  Analytics.addProduct(productId, name, category, brand, variant, price, quantity, coupon, position);
  Analytics.trackCheckout(checkoutStep, optionValue);

  // example:
  Analytics.addProduct('sku-2', 'Test Product 2', 'Category-1', 'Brand 2', 'variant-3', '2499', '1', 'FLAT10', '1');
  Analytics.addProduct('sku-2', 'Test Product 2', 'Category-1', 'Brand 2', 'variant-3', '2499', '1', 'FLAT10', '1');
  Analytics.trackCheckout(1, 'Visa');

Transaction Tracking

  Analytics.addProduct(productId, name, category, brand, variant, price, quantity, coupon, position);
  Analytics.trackTransaction(transactionId, affiliation, revenue, tax, shipping, coupon, list, step, option);

  // example:
  Analytics.addProduct('sku-2', 'Test Product 2', 'Category-1', 'Brand 2', 'variant-3', '2222', '1', 'MEN10', '1');
  Analytics.addProduct('sku-2', 'Test Product 2', 'Category-1', 'Brand 2', 'variant-3', '1111', '1', 'WOMEN10', '1');
  Analytics.trackTransaction('T1234', 'Online Store - Web', '3333', '10', '200', 'FLAT10', '', '', '');

Promotion Impressions

  Analytics.addPromo(productId, name, creative, position);
  Analytics.pageView();

  // example:
  Analytics.addPromo('PROMO_1234', 'Summer Sale', 'summer_banner2', 'banner_slot1');
  Analytics.pageView();

Note: Before tracking promotion clicks, call pageView, otherwise promotion impressions will be treated as promotion clicks.

Promotion Clicks

  Analytics.addPromo(promotionId, promotionName, creative, position);
  Analytics.promoClick(promotionName);

  // example:
  Analytics.addPromo('PROMO_1234', 'Summer Sale', 'summer_banner2', 'banner_slot1');
  Analytics.promoClick('Summer Sale');

Exception Tracking

  Analytics.trackException(description, isFatal);

  // example:
  Analytics.trackException('Function "foo" is undefined on object "bar"', true);

Online / Offline Mode

  // While in offline mode, no calls to the ga function or pushes to the gaq array are made.
  // This will queue all calls for later sending once offline mode is reset to false.
  Analytics.offline(true);

  // Reset offline mode to false
  Analytics.offline(false);

In-Memory Queues

  // If logging is enabled then all outbound calls are accessible via an in-memory array.
  // This is useful for troubleshooting and seeing the order of outbound calls with parameters.
  Analytics.log;

  // If in offline mode then all calls are queued to an in-memory array for future processing.
  // All calls queued to the offlineQueue are not outbound calls yet and hence do not show up in the log.
  Analytics.offlineQueue;

Directive

Alternatively, you can use a directive to avoid filling controllers with Analytics.trackEvent(); statements.

Note: the directive does not create an isolate scope.

  <button type="button" ga-track-event="['video', 'play', 'django.mp4']"></button>

  <!-- OR -->

  <button type="button" ga-track-event="['video', 'play', 'django.mp4', 4, true, {dimension15: 'My Custom Dimension', metric18: 8000}]"></button>

You can define the properties on your controller too, $scope.event = ['video', 'play', 'django.mp4'] and reference them.

  <button type="button" ga-track-event="event"></button>

ga-track-event-if is a conditional check. If the attribute value evaluates falsey, the event will NOT be fired. This is useful for user tracking opt-out, etc.

  <button type="button" ga-track-event="['video', 'play', 'django.mp4']" ga-track-event-if="shouldTrack"></button>

Troubleshooting

AdBlock EasyPrivacy

AdBlock has a module named EasyPrivacy that is meant to block web tracking scripts. angular-google-analytics.js gets filtered out by the EasyPrivacy blacklist.

Users who are already concatenating and minifying their scripts should not notice a problem as long as the new script name is not also on the EasyPrivacy blacklist. Alternatively, consider changing the file name manually.

Debugging Resources

Chrome Extension: Google Analytics Debugger Firefox Add-on: Google Analytics Debugger

License

As AngularJS itself, this module is released under the permissive MIT License. Your contributions are always welcome.

Development

After forking you will need to run the following from a command line to get your environment setup:

  1. npm install

After install you have the following commands available to you from a command line:

  1. npm run-script lint
  2. npm test
  3. npm run-script test-server
  4. npm run-script build or npm run-script release
  5. npm run-script stage

angular-google-analytics's People

Contributors

adam187 avatar armno avatar arndt-s avatar beasta avatar billstron avatar bradfordbarr avatar danemacaulay avatar deltaepsilon avatar doganov avatar doublesharp avatar ewoutkleinsmann avatar jonespen avatar justinsa avatar khashayar avatar kunalkukreja avatar larsdbr avatar lastlink avatar m98 avatar maxi-moto avatar mvhecke avatar ostranme avatar paul-barry-cengage avatar pkelbern avatar pmercey-gladd avatar qetr1ck-op avatar revolunet avatar sjurba avatar stramel avatar toxantron avatar tsov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

angular-google-analytics's Issues

Routing redirect causes double pageview when initially loading angular application

This happens when the application is approached without a known path in the routing configuration and trackRoutes in enabled. So any redirects due to the use of the otherwise function of angular routing result in an extra $routeChangeSuccess, which is picked up and results in another pageview to ga.

Is this known, or is there something I might be missing in relation to the routing of angular, or is this something that would be nice to fix? :)

Feature request: Expanded experiments support

Hi,

As a companion to Analytics, I am using angular-google-experiments to set up experiment variations - and was wondering if you could incorporate this functionality into the Analytics module for simplicity?
Would be good to have it all in one place..
The fork at https://github.com/eaguerralde/angular-google-experiments/blob/master/googleExperiments.js seems to have simplified the loading of the experiments js by using angularLoad. Maybe a better way than in the origin, where a timeout is used?

Thanks for creating this Analytics module! I use it in all my angular webapps!

Readme.md typo

On the front page in the last configuration block example it shows:

//Enable eCommerce module for analytics.js
AnalyticsProvider.useECommerce(true);
//Enable enhanced link attribution module for analytics.js or ga.js
AnalyticsProvider.useECommerce(true);

The second method I believe should be useEnhancedLinkAttribution

social analytics?

Hi,
how integrate social analytics with your module? facebook, G+ login, sign up? facebook share? or social interactions will be automatically reported?

regards
Stevens

Problem with Chrome extension "Google Analytics Opt-out Add-on (by Google)"

Hello, Julien!

We faced in our project with some strange problem:
When users begin to use plugin "Google Analytics Opt-out Add-on (by Google)" (https://chrome.google.com/webstore/detail/google-analytics-opt-out/fllaojicojecljbmefodhfapmkghcbnh) in Google Chrome, our application breaks.

TypeError: Cannot read property 'length' of undefined
    at $interpolate (http://localhost:8080/static/lib.js:27215:24)
    at ngBindTemplateDirective (http://localhost:8080/static/lib.js:36314:25)
    at nodeLinkFn (http://localhost:8080/static/lib.js:25212:13)
    at compositeLinkFn (http://localhost:8080/static/lib.js:24623:15)
    at compositeLinkFn (http://localhost:8080/static/lib.js:24626:13)
    at nodeLinkFn (http://localhost:8080/static/lib.js:25206:24)
    at compositeLinkFn (http://localhost:8080/static/lib.js:24623:15)
    at publicLinkFn (http://localhost:8080/static/lib.js:24528:30)
    at http://localhost:8080/static/lib.js:20247:27
    at Scope.$get.Scope.$eval (http://localhost:8080/static/lib.js:30986:28)  lib.js:28444
TypeError: Cannot read property 'childNodes' of undefined
    at compositeLinkFn (http://localhost:8080/static/lib.js:24626:36)
    at compositeLinkFn (http://localhost:8080/static/lib.js:24626:13)
    at nodeLinkFn (http://localhost:8080/static/lib.js:25206:24)
    at compositeLinkFn (http://localhost:8080/static/lib.js:24623:15)
    at publicLinkFn (http://localhost:8080/static/lib.js:24528:30)
    at http://localhost:8080/static/lib.js:20247:27
    at Scope.$get.Scope.$eval (http://localhost:8080/static/lib.js:30986:28)
    at Scope.$get.Scope.$apply (http://localhost:8080/static/lib.js:31086:23)
    at http://localhost:8080/static/lib.js:20245:15
    at Object.invoke (http://localhost:8080/static/lib.js:22661:17) undefined lib.js:28444
...

(lib.js is a concatenated version of all JS libraries)

Another strange moment, that in output HTML file "script" tags with GA are before "head" tag:
Image

When we turn off this plugin everything well.

Could you please help us with it? Any idea will be great!

Add git tag 0.0.5 for Bower

#10

bower install
bower angular-google-analytics#~0.0.5 not-cached git://github.com/revolunet/angular-google-analytics.git#~0.0.5
bower angular-google-analytics#~0.0.5 resolve git://github.com/revolunet/angular-google-analytics.git#~0.0.5
bower angular-google-analytics#~0.0.5 ENORESTARGET No tag found that was able to satisfy ~0.0.5

Additional error details:
Available versions: 0.0.4, 0.0.3, 0.0.2, 0.0.1

Event tracking with Multiple accounts

Is there a reason you only track page views for multiple accounts, why not events and others?

e.g. line 316 would become:

_analyticsJs(function () {
          if (angular.isArray(accountId)) {
            accountId.forEach(function (trackerObj) {
              $window.ga(trackerObj.name + '.send', 'event', category, action, label, value);
            });
          } else {
            $window.ga('send', 'event', category, action, label, value);
          }
          that._log('event', args);
        });

How to use Analytics with older Android devices (Android browser instead of Chrome)

I am seeing 3.3% of our traffic not show up in GA anymore... I noticed between our old app which uses old Universal Analytics and new Angular app which uses Universal Analytics (via angular-google-analytics) that the new data is missing the 'Android Browser' browser which was about 3.3% of traffic.
Both apps have the Browser 'Chrome' which has Browser Versions like 43.0.2357.124 which could be mobile or desktop.... but older Android devices should have a Browser of 'Android Browser' which versions like 4.0, 4.1, 4.2. I confirmed with an Android device that it isn't sending up the data at all by watching the Real-Time data.

Wasnt sure if someone could confirm or take a look.

Thanks,
Ari

PS here are the devices that this issue probably occurs for (pulled from the old GA data):
Samsung GT-P3113 Galaxy Tab 2 7.0
HTC 0PCV220 Desire 510
Samsung SPH-L710 Galaxy S III
Samsung GT-P5113 Galaxy Tab 2 10.1
Samsung SM-T217S Galaxy Tab 3 7.0
Samsung SGH-T999 Galaxy S III
Samsung SGH-I747 Galaxy S III

Does E-commerce work properly?

First I tried to set up E-Commerce like in the example on Github (usinig UniversalAnalytics).
I use multiple tracker -> two different Analytics ID's.

AnalyticsProvider.useECommerce(true, true);
This causes an warning:
Enhanced ecommerce plugin is enabled. Only one plugin(ecommerce/ec) can be used at a time.

After that I tried to set it up like this to try:
AnalyticsProvider.useECommerce(false, true);
This causes also a warning:
'ecommerce not set. Use AnalyticsProvider.setECommerce(true, false);'

After that I tried to set it up like this to try:
AnalyticsProvider.useECommerce(true, false);

Now I get no warning. But from the Network Tab in Chrome Dev Tools I see that no data is send by analytics. Within analytics I get no Transactions tracked. How to use E-commerce Tracking and the advanced e-commerce plugin?

Might it it be that the support for multiple trackers is missing on e-commerce? I don't see a loop for each trackker inside the e-commerce functions.

Multiple accountIds and crossDomainLinker

From this code I can see that it's not possible to use an array of accountIds and crossDomainLinker at the same time. Is there a reason for that? I'm not very familiar with analytics.js and I haven't seen a mention of this anywhere in the docs.

Src:

if (angular.isArray(accountId)) {
accountId.forEach(function (trackerObj) {
$window.ga('create', trackerObj.tracker, cookieConfig, { name: trackerObj.name });
});
} else if (crossDomainLinker) {
$window.ga('create', accountId, cookieConfig, linkerConfig);
$window.ga('require', 'linker');
if(crossLinkDomains) {
$window.ga('linker:autoLink', crossLinkDomains );
}
} else {
$window.ga('create', accountId, cookieConfig);
}

possible to start new session via sessionControl?

Just curious GA has the ability to start a new session manually via the sessionControl option:

https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#sessionControl

ga('send', 'pageview', {'sessionControl': 'start'});

How can this option be used in angular-google-analytics?
Not sure if there is a way to pass options like that to pageView manually [think i only saw example of dimension and metric data being passed with a manually pageView in the documentation]

Thanks,
Ari

setDomainName location causes reporting issues

In our AngularJS application we have noticed an issue where tracking conversions and pages aren't working when we're setting a domain name to .grasshopper.com

AnalyticsProvider.setAccount 'UA-XXXXX-X'  # replaced with our account number
AnalyticsProvider.trackPages true
AnalyticsProvider.useECommerce true
AnalyticsProvider.setDomainName '.grasshopper.com'
AnalyticsProvider.setCookieConfig({
    cookieDomain: '.grasshopper.com'
})

In a forked version if we moved the line if(domainName) $window._gaq.push(['_setDomainName', domainName]); right below window._gaq.push(['_setAccount', accountId]); then tracking conversions and pages works perfectly.

Confusing comment

I'm a bit confused as to the description for this method:

// change filename to analytics.js
AnalyticsProvider.useAnalytics(true);

It seems as though the useAnalytics() option would be toggling some setting, but the description is a bit confusing. Is that description a mistake?

Adding Custom Dimensions and Metrics

In the current implementation it is not possible to add custom Dimensions and Metrics in products.
For Example:
ga('ec:addProduct', { // Provide product details in an productFieldObject.
'id': 'P12345', // Product ID (string).
'name': 'Powerup', // Product name (string).
'category': 'Extras', // Product category (string).
'variant': 'red', // Product variant (string).
'price': '10.00', // Product price (currency).
'quantity': 2, // Product quantity (number).
'dimension4': 'strong', // Product-scoped custom dimension (string).
'metric2': 5 // Product-scoped custom metric (integer).
});

see more at: https://developers.google.com/analytics/devguides/platform/customdimsmets.

My suggestion would be to add a _addProductObject(obj) and _removeProductObject(obj) which will send the object in the same format as above.

Issues with minification

Does anyone else have issues with using these files when minifying all angular files? I keep getting unknown provider error. I tried patching up just the provider to have brackets which looked like the obvious fix, but that doesn't seem to fix the issue.

Add helper directives for simpler use

A good idea might be to provide some helper directives to simplify the use even more.

e.g.

<button ng-repeat="button in buttons" ga-track-event="button.ga"></button>

where button.ga might look something like {category: 'video', action: 'play', label: 'video.mp4'} or maybe even ['video', 'play', 'video.mp4']. Meaning you don't even need to write code in your controllers for some simple actions.

Working on a sample working version on tsov/angular-google-analytics, once ready I will propose a PR, but what are general thoughts on this one?

0.0.2 is broken

Can you please tag a new version?

0.0.2 causes a problem if you're using grunt-bower-install because it looks at the main file in bower.json - which for 0.0.2 is referencing a non-existing file (_./dist/angular-google-analytics.min.js_)

Use analytics.js by default

It took me some time to understand that I had to call AnalyticsProvider.useAnalytics(true) to make it work. I think it would be easier if analytics was used by default.

High Bounce Rate on GA

Hi,

Im getting very high bounce rate on our Google GA. Have you guys experienced anything like this?

Here is my setting:

AnalyticsProvider.setAccount('xxxx');
    AnalyticsProvider.trackPages(true);
    AnalyticsProvider.useAnalytics(true);
    AnalyticsProvider.setDomainName('domain.com');

    AnalyticsProvider.setPageEvent('$routeChangeSuccess');

Thanks

Add git tag 0.0.1 for Bower

I believe bower uses git tags to get the appropriate version of a package. You've defined the version as 0.0.1 in your bower.json, but there needs to be a git tag too.

bower not-cached    git://github.com/revolunet/angular-google-analytics.git#0.0.1
bower resolve       git://github.com/revolunet/angular-google-analytics.git#0.0.1
bower ENORESTARGET  No tag found that was able to satisfy 0.0.1

Additional error details:
No versions found in git://github.com/revolunet/angular-google-analytics.git

This should do it.

git tag -a "0.0.1"
git push origin master --tags

trackPage call doesn't work when AnalyticsProvider.trackPages(false) is configured

The Analytics.trackPage('url') call does not log anything when the AnalyticsProvider has been configured with AnalyticsProvider.trackPages(false). By the documentation, trackPages(false) is only supposed to disable automatic page tracking, but instead it actually disables the ability to make any page tracking call since it sets the trackRoutes variable to false.

It doesn't make sense that page tracking would be completely disabled, since making an explicit call should still allow me to track a page. The offending lines are in the _trackPage function where the conditional checks whether trackRoutes is true and prevents execution of the function.

`setRemoveRegExp` not documented

I was looking for a way to remove some strings from the url and in the code found setRemoveRegExp which does exactly that, but is not documented in examples.

Not possibly to set currency with analytics.js

Hi!

I'm using this for a project, where the currency is in DKK (Danish Kroner). I looked at the source, and found that the _addTrans-method takes a currency parameter, which defaults to "USD". However, the public addTrans-method doesn't take a currency-parameter, so it's not possible to override the default 'USD' currency.

Other than that, thanks for an awesome script :-)

/ Lars

Offline capabilities?

Would it be possible to implement a module so that you can generate all the metrics offline and then "push" the data to Google Analytics when being online?

Update to new Analytics code

Hi,

I guess at some point you will need to update this to use the new analytics code.

Not an issue as such, just a heads up!

Status: Receiving Data (always)

Seems GA is not receiving my data. In my module I have this pseudo code

angular.module('videomailApp', [
        '...',
        'angular-google-analytics'
    ])

    .config(function($routeProvider, $locationProvider, $logProvider, AnalyticsProvider) {
        $locationProvider.html5Mode(true)

        // https://github.com/revolunet/angular-google-analytics
        AnalyticsProvider.setAccount(clientSettings.analytics.account)
        AnalyticsProvider.trackPages(true)
        AnalyticsProvider.setDomainName(clientSettings.analytics.domainName)

        // It has both ga.js (Classic) and and analytics.js (Universal) support.
        // Call AnalyticsProvider.useAnalytics(true); to use the new Universal Analytics.

        AnalyticsProvider.useAnalytics(true)

        $routeProvider ...
    })

    // Anything inside run(...) will be run on initialization
    .run([
        '$rootScope',
        '$location',
        '$anchorScroll',
        '$compile',
        '$templateCache',
        '$log',
        'Analytics',

        // Since we are relying on automatic page tracking, we need to inject Analytics
        // at least once in your application (for example in the main run() block)

        function($rootScope, $location, $anchorScroll, $compile, $templateCache, $log, Analytics) {

           ...
        }])

    ...

Maybe you spot something I am doing wrong here or it could be a bug?

Correct setup or not?

I'm using AngularJS UI Router, and here it is my config:

.config(function(AnalyticsProvider) {
        // initial configuration
        AnalyticsProvider.setAccount('UA-XXXXXXX-X');

        // track all routes/states (or not)
        AnalyticsProvider.trackPages(true);

        // Use analytics.js instead of ga.js
        AnalyticsProvider.useAnalytics(true);

        // change page event name
        AnalyticsProvider.setPageEvent('$stateChangeSuccess');
}))

Now is there any other steps to complete? I haven't modified any states/controllers, is there anything else required? And what does the following comment means? I guess enabling 'trackPages' is enough, am I right?

.run(function(Analytics) {
  // In case you are relying on automatic page tracking, you need to inject Analytics
  // at least once in your application (for example in the main run() block)
})

Wrong _send syntax

at function _send you send an obj even though send cant receive an object. You use it on the advance e commerce functions such as _producrClick, _promoClick and _trackCart. Another problem is that you dont send the whole object but rather only the first variable.

Allow chaining to save some bytes

Instead of

            AnalyticsProvider.setAccount(...)
            AnalyticsProvider.trackPages(...)
            AnalyticsProvider.setDomainName(...)

let's save some bytes with that:

            AnalyticsProvider
                .setAccount(...)
                .trackPages(...)
                .setDomainName(...)

by returning the AnalyticsProvider instance on each of these configuration methods.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.