diff --git a/javascripts/govuk/analytics/google-analytics-universal-tracker.js b/javascripts/govuk/analytics/google-analytics-universal-tracker.js index cdc86a35..c9dd2522 100644 --- a/javascripts/govuk/analytics/google-analytics-universal-tracker.js +++ b/javascripts/govuk/analytics/google-analytics-universal-tracker.js @@ -89,6 +89,29 @@ }); }; + /* + https://developers.google.com/analytics/devguides/collection/analyticsjs/cross-domain + trackerId - the UA account code to track the domain against + name - name for the tracker + domain - the domain to track + */ + GoogleAnalyticsUniversalTracker.prototype.addLinkedTrackerDomain = function(trackerId, name, domain) { + sendToGa('create', + trackerId, + 'auto', + {'name': name}); + // Load the plugin. + sendToGa('require', 'linker'); + sendToGa(name + '.require', 'linker'); + + // Define which domains to autoLink. + sendToGa('linker:autoLink', [domain]); + sendToGa(name + '.linker:autoLink', [domain]); + + sendToGa(name + '.set', 'anonymizeIp', true); + sendToGa(name + '.send', 'pageview'); + }; + // https://developers.google.com/analytics/devguides/collection/analyticsjs/custom-dims-mets GoogleAnalyticsUniversalTracker.prototype.setDimension = function(index, value) { sendToGa('set', 'dimension' + index, String(value)); diff --git a/javascripts/govuk/analytics/tracker.js b/javascripts/govuk/analytics/tracker.js index 7382a8b1..f14b2a8d 100644 --- a/javascripts/govuk/analytics/tracker.js +++ b/javascripts/govuk/analytics/tracker.js @@ -46,5 +46,12 @@ this.classic.setCustomVariable(index, value, name, scope); }; + /* + Add a beacon to track a page in another GA account on another domain. + */ + Tracker.prototype.addLinkedTrackerDomain = function(trackerId, name, domain) { + this.universal.addLinkedTrackerDomain(trackerId, name, domain); + }; + GOVUK.Tracker = Tracker; })(); diff --git a/spec/unit/analytics/TrackerSpec.js b/spec/unit/analytics/TrackerSpec.js index d714d15d..3f7f6cbb 100644 --- a/spec/unit/analytics/TrackerSpec.js +++ b/spec/unit/analytics/TrackerSpec.js @@ -71,4 +71,25 @@ describe("GOVUK.Tracker", function() { }); }); + describe('when adding a linked domain', function() { + beforeEach(function() { + tracker = new GOVUK.Tracker(this.config); + }); + + it('adds a linked domain to universal only', function() { + window._gaq = []; + tracker.addLinkedTrackerDomain('1234', 'test', 'www.example.com'); + + expect(window._gaq).toEqual([]); + var allArgs = window.ga.calls.allArgs() + expect(allArgs).toContain(['create', '1234', 'auto', {'name': 'test'}]); + expect(allArgs).toContain(['require', 'linker']); + expect(allArgs).toContain(['test.require', 'linker']); + expect(allArgs).toContain(['linker:autoLink', ['www.example.com']]); + expect(allArgs).toContain(['test.linker:autoLink', ['www.example.com']]); + expect(allArgs).toContain(['test.set', 'anonymizeIp', true]); + expect(allArgs).toContain(['test.send', 'pageview']); + }); + }); + });