govuk_publishing_components icon indicating copy to clipboard operation
govuk_publishing_components copied to clipboard

Use Google snippet for GTM in analytics JavaScript

Open andysellick opened this issue 2 years ago • 0 comments

What

  • include the code snippet from Google in our code for running GTM as part of our new analytics code
  • note that this will not work without the id, auth and preview values, which have to be created separately before the analytics code is called in static

Note that none of this code will be executed in production yet. This also depends upon the correct environment variables being set for the GTM code variables (see related PR, not ready yet).

How this works:

  • static includes analytics-ga4.js (only on integration)
  • static gets the GTM variables for id, auth and preview from environment variables using the functionality available through js.erb and sets them as JS variables inside the window.analyticsGA4.vars object
  • static then calls window.GOVUK.analyticsGA4.init() (init-ga4.js in the gem)
  • the analytics code is set up and configured, beginning first with the core.load function in ga4-core.js, which runs the Google code snippet, inserting the variables for id, auth and preview from the window.analyticsGA4.vars object

A few thoughts on this:

  • I'm not sure what tests can be written for ga4-core.js as all it currently does is run the code snippet from Google, but I'm open to suggestions
  • 'core' was the best name I could think of for this code, but I'm not sure I like it, so again any suggestions welcome
  • core seems a bit empty at the moment, but I'm planning for it to be the home for more code, specifically the generic 'push things to the dataLayer' function

Why

We're moving to integrate this analytics code fully with the cookie consent mechanism, which means no code from Google will be called unless users consent to cookies.

Visual Changes

None.

Trello card: https://trello.com/c/vrMj18et/353-integrate-gtm-with-cookie-consent-mechanism

andysellick avatar Sep 09 '22 13:09 andysellick