Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add support for Google Tag Manager #631

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/initialize.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ import {
import {
configure as configureAnalytics, SegmentAnalyticsService, identifyAnonymousUser, identifyAuthenticatedUser,
} from './analytics';
import { GoogleAnalyticsLoader } from './scripts';
import { GoogleAnalyticsLoader, GoogleTagManagerLoader } from './scripts';
import {
getAuthenticatedHttpClient,
configure as configureAuth,
Expand Down Expand Up @@ -290,7 +290,7 @@ export async function initialize({
analyticsService = SegmentAnalyticsService,
authService = AxiosJwtAuthService,
authMiddleware = [],
externalScripts = [GoogleAnalyticsLoader],
externalScripts = [GoogleAnalyticsLoader, GoogleTagManagerLoader],
requireAuthenticatedUser: requireUser = false,
hydrateAuthenticatedUser: hydrateUser = false,
messages,
Expand Down
60 changes: 60 additions & 0 deletions src/scripts/GoogleTagManagerLoader.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/**
* @implements {GoogleTagManagerLoader}
* @memberof module:GoogleTagManager
*/
class GoogleTagManagerLoader {
constructor({ config }) {
this.gtmId = config.GOOGLE_TAG_MANAGER_ID;
this.gtmArgs = '';
if (config.GOOGLE_TAG_MANAGER_AUTH) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could you please add respective config in the env as well

Copy link
Author

@xitij2000 xitij2000 Mar 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure where else it needs to be added. It's an optional feature, so it should not be there in the default config.

this.gtmArgs += `&gtm_auth=${config.GOOGLE_TAG_MANAGER_AUTH}`;
}
if (config.GOOGLE_TAG_MANAGER_PREVIEW) {
this.gtmArgs += `&gtm_preview=${config.GOOGLE_TAG_MANAGER_PREVIEW}`;
}
if (config.GOOGLE_TAG_MANAGER_ADDNL_ARGS) {
if (!config.GOOGLE_TAG_MANAGER_ADDNL_ARGS.startsWith('&')) {
this.gtmArgs += '&';
}
this.gtmArgs += config.GOOGLE_TAG_MANAGER_ADDNL_ARGS;
}
}

loadScript() {
if (!this.gtmId) {
return;
}

global.googleTagManager = global.googleTagManager || [];
const { googleTagManager } = global;

// If the snippet was invoked do nothing.
if (googleTagManager.invoked) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[curious-passerby] Could you give an example where loadScript would be called twice? I feel like it is only being called from initialize, and initialize should only be called once in an app, right?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@zawan-ila I did not put much thought into this, I copied the basic framework for the GoogleAnalyticsLoader script so I assumed that tracking the invocation and ensuring it is loaded only once was being done in that script because it was a possibility.

return;
}

// Invoked flag, to make sure the snippet is never invoked twice.
googleTagManager.invoked = true;

googleTagManager.load = (key, args, options) => {
const scriptSrc = document.createElement('script');
scriptSrc.type = 'text/javascript';
scriptSrc.async = true;
scriptSrc.innerHTML = `
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl+'${args}';f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','${key}');
`;
document.head.insertBefore(scriptSrc, document.head.getElementsByTagName('script')[0]);

googleTagManager._loadOptions = options; // eslint-disable-line no-underscore-dangle
};

// Load GoogleTagManager with your key.
googleTagManager.load(this.gtmId, this.gtmArgs);
}
}

export default GoogleTagManagerLoader;
117 changes: 117 additions & 0 deletions src/scripts/GoogleTagManagerLoader.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import { GoogleTagManagerLoader } from './index';

const gtmId = 'test-key';

describe('GoogleTagManager', () => {
let gtmScriptId;
let firstScriptTag;

beforeEach(() => {
window.googleTagManager = [];
document.head.innerHTML = '<title>Testing</title><meta charset="utf-8" /><script id="testing"></script>';
document.body.innerHTML = '<script id="stub" />';
gtmScriptId = `<script src="https://www.googletagmanager.com/gtm.js?id=${gtmId}" />`;
});

function loadGoogleTagManager(scriptData) {
const script = new GoogleTagManagerLoader(scriptData);
script.loadScript();
}

function setupConfigData(configVars) {
const data = {
config: {
...configVars,
},
};
return data;
}

describe('with valid GOOGLE_TAG_MANAGER_ID', () => {
let data;
beforeEach(() => {
data = setupConfigData({ GOOGLE_TAG_MANAGER_ID: gtmId });
loadGoogleTagManager(data);
expect(global.googleTagManager.invoked)
.toBe(true);
});

it('should initialize google tag manager', () => {
expect(document.head.children[0])
.toContainHTML('<title>Testing</title>');
// The first inserted script tag should be the first script tag
// eslint-disable-next-line prefer-destructuring
firstScriptTag = document.head.getElementsByTagName('script')[0];
expect(firstScriptTag)
.toContainHTML(gtmScriptId);
});

it('should not initialize google tag manager twice', () => {
const scriptCountPre = document.head.getElementsByTagName('script').length;
loadGoogleTagManager(data);
const scriptCountPost = document.head.getElementsByTagName('script').length;
expect(scriptCountPost)
.toEqual(scriptCountPre);
});
});

describe.each([
{
tag: 'PREVIEW',
value: 'preview-xyz',
queryParam: 'gtm_preview=preview-xyz',
},
{
tag: 'AUTH',
value: 'auth-xyz',
queryParam: 'gtm_auth=auth-xyz',
},
{
tag: 'ADDNL_ARGS',
value: 'gtm_cookies_win=x',
queryParam: 'gtm_cookies_win=x',
},
{
tag: 'ADDNL_ARGS',
value: '&gtm_cookies_win=x',
queryParam: 'gtm_cookies_win=x',
},
])('with other valid Google Tag Manager options', ({
tag,
value,
queryParam,
}) => {
it(`should correctly handle the GOOGLE_TAG_MANAGER_${tag} option`, () => {
const data = setupConfigData({
GOOGLE_TAG_MANAGER_ID: gtmId,
[`GOOGLE_TAG_MANAGER_${tag}`]: value,
});
loadGoogleTagManager(data);
// eslint-disable-next-line prefer-destructuring
firstScriptTag = document.head.getElementsByTagName('script')[0];
const scriptURL = new URL(firstScriptTag.src);
// Options shouldn't get merged.
expect(scriptURL.searchParams.size)
.toBe(2);
expect(scriptURL.search)
.toContain(queryParam);
});
});

describe('with invalid GOOGLE_TAG_MANAGER_ID', () => {
beforeEach(() => {
const data = setupConfigData({ GOOGLE_TAG_MANAGER_ID: '' });
loadGoogleTagManager(data);
expect(global.googleTagManager.invoked)
.toBeFalsy();
});

it('should not initialize google analytics', () => {
Array.from(document.head.getElementsByTagName('script')).forEach(scriptNode => {
expect(scriptNode)
.not
.toContainHTML(gtmScriptId);
});
});
});
});
1 change: 1 addition & 0 deletions src/scripts/index.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
/* eslint-disable import/prefer-default-export */
export { default as GoogleAnalyticsLoader } from './GoogleAnalyticsLoader';
export { default as GoogleTagManagerLoader } from './GoogleTagManagerLoader';