Skip to content

Commit

Permalink
Merge pull request #966 from alphagov/PP-12559_upgrade_to_GA4
Browse files Browse the repository at this point in the history
PP-12559 Migrate from google analytics to gtag
  • Loading branch information
hjvoid authored Jun 21, 2024
2 parents 7df43f7 + ca82d00 commit 0826306
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 92 deletions.
99 changes: 13 additions & 86 deletions source/javascripts/analytics.js
Original file line number Diff line number Diff line change
@@ -1,99 +1,26 @@
/**
* Load and configure google analytics, managed independently from the core
* Load and configure google analytics (GA4), managed independently from the core
* tech docs gem to allow running it exclusively based on custom
* payments.service.gov.uk analytics consent rules.
*/
function initialiseGoogleAnalytics() {
loadGoogleAnalytics()
}

function getCookieDomain () {
return window.location.hostname.replace(/^(www.){0,1}(docs.){0,1}/, '.')
}

/**
* Allow only fetching files from Google if consent has been provided by the
* user.
* Forked from https://github.com/alphagov/tech-docs-gem/blob/90b6ac06e79aa155592f6ffe08d522b922483c6c/lib/source/layouts/_analytics.erb
*/
function loadGoogleAnalytics() {
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-72121642-9', getCookieDomain());
ga('set', 'anonymizeIp', true);
ga('set', 'displayFeaturesTask', null);
ga('set', 'transport', 'beacon');
ga('set', 'page', location.pathname+location.search+location.hash);
ga('send', 'pageview');
function initialiseGtag() {
var gtagScript = document.createElement('script')
gtagScript.async = true
gtagScript.setAttribute('src', 'https://www.googletagmanager.com/gtag/js?id=G-XE9K05CFFE')
document.head.appendChild(gtagScript)

configureGoogleAnalytics(jQuery)
}
window.dataLayer = window.dataLayer || [];

/**
* Customise Google Analytics for the tech docs format, only configured provided
* user consent and fetched analytics files from Google.
* Forked from https://github.com/alphagov/tech-docs-gem/blob/f28d9dced2fbc0bc7d221ed82f696b81c958a03e/lib/assets/javascripts/_analytics.js
*/
function configureGoogleAnalytics($) {
function trackLinkClick (action, $element) {
var linkText = $.trim($element.text())
var linkURL = $element.attr('href')
var label = linkText + '|' + linkURL

ga(
'send',
'event',
'SM Technical Documentation', // Event Category
action, // Event Action
label // Event Label
)
}

function linkTrackingEventHandler (action) {
return function () {
trackLinkClick(action, $(this))
}
}

function catchBrokenFragmentLinks () {
var fragment = window.location.hash
var $target = $(fragment)
if (!$target.get(0)) {
ga(
'send',
'event',
'Broken fragment ID', // Event Category
'pageview', // Event Action
window.location.pathname + fragment // Event Label
)
function gtag() {
dataLayer.push(arguments);
}
}

$(document).on('ready', function () {
if (typeof ga === 'undefined') {
return
}

$('.technical-documentation a').on('click', linkTrackingEventHandler('inTextClick'))
$('.header a').on('click', linkTrackingEventHandler('topNavigationClick'))
$('.toc a').on('click', linkTrackingEventHandler('tableOfContentsNavigationClick'))
catchBrokenFragmentLinks()

// Borrowed from:
// https://github.com/alphagov/govuk_frontend_toolkit/blob/master/javascripts/govuk/analytics/analytics.js
window.stripPIIFromString = function (string) {
var EMAIL_PATTERN = /[^\s=/?&]+(?:@|%40)[^\s=/?&]+/g
var POSTCODE_PATTERN = /[A-PR-UWYZ][A-HJ-Z]?[0-9][0-9A-HJKMNPR-Y]?(?:[\s+]|%20)*[0-9][ABD-HJLNPQ-Z]{2}/gi
var DATE_PATTERN = /\d{4}(-?)\d{2}(-?)\d{2}/g
var stripped = string.replace(EMAIL_PATTERN, '[email]')
.replace(DATE_PATTERN, '[date]')
.replace(POSTCODE_PATTERN, '[postcode]')
return stripped
gtagScript.onload = function () {
gtag('js', new Date());
gtag('config', 'G-XE9K05CFFE');
}
})
}

window.initialiseGoogleAnalytics = initialiseGoogleAnalytics
window.initialiseGtag = initialiseGtag
4 changes: 2 additions & 2 deletions source/javascripts/application.min.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@

window.addEventListener('DOMContentLoaded', function() {
if (window.GovUkPay) {
window.GovUkPay.cookies.showBannerIfConsentNotSet(window.initialiseGoogleAnalytics)
window.GovUkPay.cookies.showBannerIfConsentNotSet(window.initialiseGtag)

if (window.GovUkPay.cookies.hasAnalyticsConsent()) {
window.initialiseGoogleAnalytics()
window.initialiseGtag()
}
}
})
Expand Down
8 changes: 4 additions & 4 deletions source/javascripts/application.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ describe("Application JS", () => {
document.cookie = "govuk_pay_cookie_policy=;expires=Thu, 01 Jan 1970 00:00:00 UTC;domain=.example.org";

window.GovUkPay.cookies.showBannerIfConsentNotSet = jest.fn()
window.initialiseGoogleAnalytics = jest.fn()
window.initialiseGtag = jest.fn()

// Override Document ready function in the test
window.addEventListener = (event, callback) => {
Expand All @@ -33,7 +33,7 @@ describe("Application JS", () => {
require("./application")

expect(
window.initialiseGoogleAnalytics.mock.calls.length
window.initialiseGtag.mock.calls.length
).toBe(0);
});

Expand All @@ -43,7 +43,7 @@ describe("Application JS", () => {
require("./application")

expect(
window.initialiseGoogleAnalytics.mock.calls.length
window.initialiseGtag.mock.calls.length
).toBe(0);
});

Expand All @@ -54,7 +54,7 @@ describe("Application JS", () => {
require("./application")

expect(
window.initialiseGoogleAnalytics.mock.calls.length
window.initialiseGtag.mock.calls.length
).toBe(1);
});
});

0 comments on commit 0826306

Please sign in to comment.