Skip to content

Commit

Permalink
feat: Add support for Google Tag Manger
Browse files Browse the repository at this point in the history
This change adds support for Google Tag Manager along with some common options for Google Tag Manager.
  • Loading branch information
xitij2000 committed Jan 4, 2024
1 parent ad936a2 commit 8d1a426
Show file tree
Hide file tree
Showing 4 changed files with 180 additions and 2 deletions.
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) {
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) {
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

Check failure on line 24 in src/scripts/GoogleTagManagerLoader.test.js

View workflow job for this annotation

GitHub Actions / tests

Missing trailing comma
}

Check failure on line 25 in src/scripts/GoogleTagManagerLoader.test.js

View workflow job for this annotation

GitHub Actions / tests

Missing trailing comma
};
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
firstScriptTag = document.head.getElementsByTagName('script')[0];

Check failure on line 43 in src/scripts/GoogleTagManagerLoader.test.js

View workflow job for this annotation

GitHub Actions / tests

Use array destructuring
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);
});

Check failure on line 54 in src/scripts/GoogleTagManagerLoader.test.js

View workflow job for this annotation

GitHub Actions / tests

Block must not be padded by blank lines

});

describe.each([
{
tag: 'PREVIEW',
value: 'preview-xyz',
queryParam: 'gtm_preview=preview-xyz'

Check failure on line 62 in src/scripts/GoogleTagManagerLoader.test.js

View workflow job for this annotation

GitHub Actions / tests

Missing trailing comma
},
{
tag: 'AUTH',
value: 'auth-xyz',
queryParam: 'gtm_auth=auth-xyz'

Check failure on line 67 in src/scripts/GoogleTagManagerLoader.test.js

View workflow job for this annotation

GitHub Actions / tests

Missing trailing comma
},
{
tag: 'ADDNL_ARGS',
value: 'gtm_cookies_win=x',
queryParam: 'gtm_cookies_win=x'

Check failure on line 72 in src/scripts/GoogleTagManagerLoader.test.js

View workflow job for this annotation

GitHub Actions / tests

Missing trailing comma
},
{
tag: 'ADDNL_ARGS',
value: '&gtm_cookies_win=x',
queryParam: 'gtm_cookies_win=x'

Check failure on line 77 in src/scripts/GoogleTagManagerLoader.test.js

View workflow job for this annotation

GitHub Actions / tests

Missing trailing comma
},
])('with other valid Google Tag Manager options', ({
tag,
value,
queryParam

Check failure on line 82 in src/scripts/GoogleTagManagerLoader.test.js

View workflow job for this annotation

GitHub Actions / tests

Missing trailing comma
}) => {
it(`should correctly handle the GOOGLE_TAG_MANAGER_${tag} option`, () => {
let data = setupConfigData({

Check failure on line 85 in src/scripts/GoogleTagManagerLoader.test.js

View workflow job for this annotation

GitHub Actions / tests

'data' is never reassigned. Use 'const' instead
GOOGLE_TAG_MANAGER_ID: gtmId,
[`GOOGLE_TAG_MANAGER_${tag}`]: value
});
loadGoogleTagManager(data);
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(() => {
let data = setupConfigData({ GOOGLE_TAG_MANAGER_ID: '' });
loadGoogleTagManager(data);
expect(global.googleTagManager.invoked)
.toBeFalsy();
});

it('should not initialize google analytics', () => {
for (var scriptTag of document.head.getElementsByTagName('script')) {
expect(scriptTag)
.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';

0 comments on commit 8d1a426

Please sign in to comment.