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 Manger #1

Closed
Closed
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 @@ -59,7 +59,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 @@ -250,7 +250,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;
118 changes: 118 additions & 0 deletions src/scripts/GoogleTagManagerLoader.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import { GoogleTagManagerLoader } from './index';

const gtmId = 'test-key';

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

beforeEach(() => {
window.googleTagManager = [];
document.head.innerHTML = '<title>Title</title><meta charset="utf-8" /><script id="testing"></script>';
document.body.innerHTML = '<script id="stub" />';

gtmScriptSrc = `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].innerHTML)
.toBe('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.src)
.toBe(gtmScriptSrc);
});

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.src)
.not
.toBe(gtmScriptSrc);
});
});
});
});
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';