Skip to content

Commit

Permalink
Remove dependency on .js.erb and puppet for loading our analytics
Browse files Browse the repository at this point in the history
This change creates a JavaScript file which will load in our analytics variables depending on the current domain that the user is on. We cannot use puppet anymore due to the new infrastructure. .js.erb is deprecated and so is use of static.
  • Loading branch information
AshGDS committed Jan 13, 2023
1 parent a0131d2 commit 0c0afc3
Show file tree
Hide file tree
Showing 10 changed files with 477 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -11,6 +11,7 @@

* Add GA4 tracking to related navigation ([PR #3179](https://github.com/alphagov/govuk_publishing_components/pull/3179))
* Add Youtube Embed Support to the ImageCard Component ([PR #3156](https://github.com/alphagov/govuk_publishing_components/pull/3156))
* Remove dependency on .js.erb and puppet for loading our analytics ([PR #3145](https://github.com/alphagov/govuk_publishing_components/pull/3145))

## 34.3.0

Expand Down
@@ -0,0 +1,135 @@
// For Universal Analytics' cross domain tracking.
window.GOVUK.analytics = window.GOVUK.analytics || {}
window.GOVUK.analytics.linkedDomains = [
'access.service.gov.uk',
'access.tax.service.gov.uk',
'account.companieshouse.gov.uk',
'accounts.manage-apprenticeships.service.gov.uk',
'account.publishing.service.gov.uk',
'add-driving-licence-check-code.service.gov.uk',
'analyse-school-performance.service.gov.uk',
'appeal-tax-tribunal.service.gov.uk',
'apply-basic-criminal-record-check.service.gov.uk',
'apply-blue-badge.service.gov.uk',
'apply-company-tachograph-card.service.gov.uk',
'apply-for-bankruptcy.service.gov.uk',
'apply-for-debt-relief-order.service.gov.uk',
'apply-for-environmental-permit.service.gov.uk',
'apply-for-eu-settled-status.homeoffice.gov.uk',
'apply-for-innovation-funding.service.gov.uk',
'apply-for-refugee-integration-loan.service.gov.uk',
'apply-licence.ozone-depleting-substances.service.gov.uk',
'apply-quota.fluorinated-gas.service.gov.uk',
'apply-quota.ozone-depleting-substances.service.gov.uk',
'apprenticeships.gov.uk',
'beta.companieshouse.gov.uk',
'biometric-residence-permit.service.gov.uk',
'businessreadinessfund.beis.gov.uk',
'catchreturn.service.gov.uk',
'checklegalaid.service.gov.uk',
'check-mot.service.gov.uk',
'check-payment-practices.service.gov.uk',
'check-vehicle-recalls.service.gov.uk',
'civil-service-careers.gov.uk',
'civilservicejobs.service.gov.uk',
'claim.redundancy-payments.service.gov.uk',
'claim-power-of-attorney-refund.service.gov.uk',
'compare-school-performance.service.gov.uk',
'complete-deputy-report.service.gov.uk',
'contractsfinder.service.gov.uk',
'coronavirus.data.gov.uk',
'coronavirus-business-volunteers.service.gov.uk',
'coronavirus-shielding-support.service.gov.uk',
'coronavirus-vulnerable-people.service.gov.uk',
'courttribunalfinder.service.gov.uk',
'create-energy-label.service.gov.uk',
'create-qr-code-poster.service.gov.uk',
'cymraeg.registertovote.service.gov.uk',
'dartford-crossing-charge.service.gov.uk',
'design-system.service.gov.uk',
'devtracker.dfid.gov.uk',
'digitalmarketplace.service.gov.uk',
'eforms.homeoffice.gov.uk',
'electronic-visa-waiver.service.gov.uk',
'employmenttribunals.service.gov.uk',
'eu-settled-status-enquiries.service.gov.uk',
'faster-uk-entry.service.gov.uk',
'finance.manage-apprenticeships.service.gov.uk',
'find-and-update.company-information.service.gov.uk',
'findapprenticeship.service.gov.uk',
'find-coronavirus-support.service.gov.uk',
'find-employer-schemes.education.gov.uk',
'flood-map-for-planning.service.gov.uk',
'flood-warning-information.service.gov.uk',
'follow.company-information.service.gov.uk',
'gender-pay-gap.service.gov.uk',
'get-fishing-licence.service.gov.uk',
'get-information-schools.service.gov.uk',
'gro.gov.uk',
'helpforhouseholds.campaign.gov.uk',
'helpwithcourtfees.service.gov.uk',
'help-with-prison-visits.service.gov.uk',
'identity.company-information.service.gov.uk',
'identity-sandbox.company-information.service.gov.uk',
'import-products-animals-food-feed.service.gov.uk',
'lastingpowerofattorney.service.gov.uk',
'live.email-dvla.service.gov.uk',
'live.dvla-web-chat.service.gov.uk',
'loststolenpassport.service.gov.uk',
'makeaplea.service.gov.uk',
'managefleetvehicles.service.gov.uk',
'manage-apprenticeships.service.gov.uk',
'manage-fish-exports.service.gov.uk',
'manage-quota.fluorinated-gas.service.gov.uk',
'manage-water-abstraction-impoundment-licence.service.gov.uk',
'match.redundancy-payments.service.gov.uk',
'mot-testing.service.gov.uk',
'nominate-uk-honour.service.gov.uk',
'notice.redundancy-payments.service.gov.uk',
'passport.service.gov.uk',
'paydvlafine.service.gov.uk',
'payments.service.gov.uk',
'publish-payment-practices.service.gov.uk',
'queens-awards-enterprise.service.gov.uk',
'recruit.manage-apprenticeships.service.gov.uk',
'register.fluorinated-gas.service.gov.uk',
'register-trailer.service.gov.uk',
'register.ozone-depleting-substances.service.gov.uk',
'registertovote.service.gov.uk',
'register-vehicle.service.gov.uk',
'registers.service.gov.uk',
'reminders.mot-testing.service.gov.uk',
'renewable-heat-calculator.service.gov.uk',
'reply-jury-summons.service.gov.uk',
'report-director-conduct.service.gov.uk',
'report.fluorinated-gas.service.gov.uk',
'report.ozone-depleting-substances.service.gov.uk',
'right-to-rent.homeoffice.gov.uk',
'right-to-work.service.gov.uk',
'ruralpayments.service.gov.uk',
'schools-financial-benchmarking.service.gov.uk',
'secured.studentfinanceni.co.uk',
'secured.studentfinancewales.co.uk',
'selfservice.payments.service.gov.uk',
'send-money-to-prisoner.service.gov.uk',
'signin.service.gov.uk',
'sorn.service.gov.uk',
'staff.helpwithcourtfees.service.gov.uk',
'student-finance.service.gov.uk',
'tax.service.gov.uk',
'teacherservices.education.gov.uk',
'teaching-vacancies.service.gov.uk',
'to-visit-or-stay-in-the-uk.homeoffice.gov.uk',
'trade-tariff.service.gov.uk',
'tribunal-response.employmenttribunals.service.gov.uk',
'ukri.org',
'update-student-loan-employment-details.service.gov.uk',
'vehicle-operator-licensing.service.gov.uk',
'vehicleenquiry.service.gov.uk',
'viewdrivingrecord.service.gov.uk',
'view-and-prove-your-rights.homeoffice.gov.uk',
'view-immigration-status.service.gov.uk',
'visa-address-update.service.gov.uk',
'visas-immigration.service.gov.uk',
'your-defra-account.defra.gov.uk'
]
Expand Up @@ -6,4 +6,13 @@

document.addEventListener('DOMContentLoaded', function () {
window.GOVUK.modules.start()

// if statements ensure these functions don't execute during testing
if (typeof window.GOVUK.analyticsGa4.vars === 'undefined') {
window.GOVUK.loadAnalytics.loadGa4()
}

if (typeof window.GOVUK.analyticsInit === 'undefined') {
window.GOVUK.loadAnalytics.loadUa()
}
})
113 changes: 113 additions & 0 deletions app/assets/javascripts/govuk_publishing_components/load-analytics.js
@@ -0,0 +1,113 @@
//= require govuk_publishing_components/analytics
//= require govuk_publishing_components/analytics-ga4
//= require govuk_publishing_components/analytics/linked-domains

window.GOVUK.loadAnalytics = {
productionDomains: [
'www.gov.uk',
'www-origin.publishing.service.gov.uk'
],
stagingDomains: [
'www.staging.publishing.service.gov.uk',
'www-origin.staging.publishing.service.gov.uk'
],
integrationDomains: [
'www.integration.publishing.service.gov.uk',
'www-origin.integration.publishing.service.gov.uk'
],
developmentDomains: [
'localhost', '127.0.0.1', '0.0.0.0'
],

// For Universal Analytics' cross domain tracking. linkedDomains is defined by the require statement at the top of the file.
linkedDomains: window.GOVUK.analytics.linkedDomains,

ga4EnvironmentVariables: {
// initialiseGA4 is used to enable/disable GA4 on specific environments
production: {
initialiseGA4: true
},
staging: {
initialiseGA4: true,
auth: 'oJWs562CxSIjZKn_GlB5Bw',
preview: 'env-5'
},
integration: {
initialiseGA4: true,
auth: 'C7iYdcsOlYgGmiUJjZKrHQ',
preview: 'env-4'
},
development: {
initialiseGA4: true,
auth: 'bRiZ-jiEHtw6hHpGd6dF9w',
preview: 'env-3'
}
},

loadUa: function (currentDomain) {
currentDomain = currentDomain || window.location.hostname

// Universal Analytics variables
window.GOVUK.analyticsVars = window.GOVUK.analyticsVars || {}
window.GOVUK.analyticsVars.primaryLinkedDomains = ['account.gov.uk']
window.GOVUK.analyticsVars.linkedDomains = this.linkedDomains
window.GOVUK.analyticsVars.gaProperty = 'UA-UNSET'
window.GOVUK.analyticsVars.gaPropertyCrossDomain = 'UA-UNSET'

if (this.arrayContains(currentDomain, this.productionDomains)) {
window.GOVUK.analyticsVars.gaProperty = 'UA-26179049-1'
window.GOVUK.analyticsVars.gaPropertyCrossDomain = 'UA-145652997-1'
} else if (this.arrayContains(currentDomain, this.stagingDomains)) {
window.GOVUK.analyticsVars.gaProperty = 'UA-26179049-20'
window.GOVUK.analyticsVars.gaPropertyCrossDomain = 'UA-145652997-1'
} else if (this.arrayContains(currentDomain, this.integrationDomains)) {
window.GOVUK.analyticsVars.gaProperty = 'UA-26179049-22'
window.GOVUK.analyticsVars.gaPropertyCrossDomain = 'UA-145652997-1'
}

// Load universal analytics
if (typeof window.GOVUK.analyticsInit !== 'undefined') {
window.GOVUK.analyticsInit()
}
},

loadGa4: function (currentDomain) {
currentDomain = currentDomain || window.location.hostname
var environment = ''

// Categorise current environment
if (this.arrayContains(currentDomain, this.productionDomains)) {
environment = 'production'
} else if (this.arrayContains(currentDomain, this.stagingDomains)) {
environment = 'staging'
} else if (this.arrayContains(currentDomain, this.integrationDomains)) {
environment = 'integration'
} else if (this.arrayContains(currentDomain, this.developmentDomains) || currentDomain.indexOf('.dev.gov.uk') !== -1) {
environment = 'development'
}

// If we recognise the environment (i.e. the string isn't empty), load in GA4
if (environment) {
// If analytics-ga4.js exists and our detected environment has 'initialiseGA4' set to true, load GA4.
if (typeof window.GOVUK.analyticsGa4.init !== 'undefined' && this.ga4EnvironmentVariables[environment].initialiseGA4) {
window.GOVUK.analyticsGa4 = window.GOVUK.analyticsGa4 || {}
window.GOVUK.analyticsGa4.vars = window.GOVUK.analyticsGa4.vars || {}
window.GOVUK.analyticsGa4.vars.id = 'GTM-MG7HG5W'
window.GOVUK.analyticsGa4.vars.auth = this.ga4EnvironmentVariables[environment].auth
window.GOVUK.analyticsGa4.vars.preview = this.ga4EnvironmentVariables[environment].preview
window.GOVUK.analyticsGa4.vars.environment = environment // Used for testing and debugging

window.GOVUK.analyticsGa4.vars.gem_version = 'not found'
var gemMeta = document.querySelector('meta[name="govuk:components_gem_version"]')
if (gemMeta) {
window.GOVUK.analyticsGa4.vars.gem_version = gemMeta.getAttribute('content')
}
window.GOVUK.analyticsGa4.init()
}
}
},

arrayContains: function (valueToFind, array) {
return array.indexOf(valueToFind) !== -1
}
}
Expand Up @@ -58,6 +58,7 @@
"lux-reporter-script": path_to_javascript("govuk_publishing_components/vendor/lux/lux-reporter")
}
} %>
<%= javascript_include_tag "govuk_publishing_components/load-analytics" %>
<%= csrf_meta_tags %>
Expand All @@ -78,6 +79,9 @@
<% # The default og:image is added below :head so that scrapers see any custom metatags first, and this is just a fallback %>
<meta property="og:image" content="<%= asset_path "govuk-opengraph-image.png" %>">
<% # Used for Google Analytics 4 debugging %>
<meta name="govuk:components_gem_version" content="<%= GovukPublishingComponents::VERSION %>" />
<%= yield :head %>
</head>
<%= tag.body class: body_css_classes do %>
Expand Down
2 changes: 1 addition & 1 deletion docs/analytics/analytics.md
Expand Up @@ -170,7 +170,7 @@ named tracker, and sessions will persist to the other domain.

Once a service starts sending analytics data to the shared GA property and has configured their system to include `www.gov.uk` in their cross domain linking, we must also configure `www.gov.uk` to include their domain in our cross linker configuration.

Add the domain of the service to [`init.js.erb`](https://github.com/alphagov/static/blob/main/app/assets/javascripts/analytics.js.erb).
Add the domain of the service to [linked-domains.js](https://github.com/alphagov/govuk_publishing_components/tree/main/app/assets/javascripts/govuk_publishing_components/analytics/linked-domains.js).

Here's an [example of an earlier PR](https://github.com/alphagov/static/pull/1845) to do this.

Expand Down
17 changes: 17 additions & 0 deletions docs/load-analytics.md
@@ -0,0 +1,17 @@
# Loading analytics into our applications

For analytics tracking, each environment (production, staging, integration, development) uses different environment variables. These environment variables are used to determine which dashboard analytics data is sent to. This is useful to us for testing and debugging, as we can test our analytics in isolated environments. Therefore, we want to be able to set different environment variables depending on which environment we are in. This needs to happen before our analytics code is initialised, so `load-analytics.js` executes before our analytics code is run.

Therefore, `load-analytics.js` has been written to do the following:

1. Grab the current domain that the code is running on using `window.location.hostname`.
2. Determine the environment you are on by comparing your domain against hardcoded categorised domains.
3. Set the correct environment variables for both Universal Analytics, and Google Analytics 4, depending on the environment you are on. These are also hardcoded now.
4. Kick off the initialisation of analytics by running their respective `init()` functions, which will then run the `ga4-core.js` code and the UA tracking initialisation code.
5. The `ga4-core.js` / UA code then makes use of these environment variables. It can access them as they are set on the JavaScript `window` object.

The Google Analytics 4 environment variables are:

- `id` - this is the Google Tag Manager ID used to identify our organisation so that analytics data is sent to the right account.
- `preview` - this is an optional variable that is used to determine what GTM environment the analytics data is sent to. If this is empty, analytics data is sent to the production dashboard. If you wanted to have your integration analytics to an 'integration' dashboard, you would populate this variable with the relevant value.
- `auth` - this is used to authenticate analytics data being sent to another dashboard, such as an 'integration' dashboard. This can be determined through the browser so they're not classified as secret.

0 comments on commit 0c0afc3

Please sign in to comment.