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 a Google Tag Manager loader #12

Merged
merged 2 commits into from
Nov 13, 2024
Merged
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
22 changes: 17 additions & 5 deletions src/components/Footer.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ import PropTypes from 'prop-types';
import { injectIntl, intlShape } from '@edx/frontend-platform/i18n';
import { sendTrackEvent } from '@edx/frontend-platform/analytics';
import {
APP_CONFIG_INITIALIZED, ensureConfig, getConfig, subscribe,
APP_PUBSUB_INITIALIZED, APP_CONFIG_INITIALIZED, ensureConfig, getConfig, mergeConfig, subscribe,
} from '@edx/frontend-platform';
import { loadExternalScripts } from '@edx/frontend-platform/initialize';
import { AppContext } from '@edx/frontend-platform/react';

import { hydrateAuthenticatedUser } from '@edx/frontend-platform/auth';
Expand All @@ -14,13 +15,28 @@ import FooterLinks from './footer-links/FooterNavLinks';
import FooterSocial from './footer-links/FooterSocialLinks';
import parseEnvSettings from '../utils/parseData';
import ModalToS from './modal-tos';
import GoogleTagManagerLoader from '../services/gtmLoader';

ensureConfig([
'LMS_BASE_URL',
'LOGO_TRADEMARK_URL',
'LOGO_POWERED_BY',
], 'Footer component');

subscribe(APP_PUBSUB_INITIALIZED, () => {
mergeConfig({
GOOGLE_TAG_MANAGER_ID: process.env.GOOGLE_TAG_MANAGER_ID || '',
GOOGLE_TAG_MANAGER_ENVIRONMENT: process.env.GOOGLE_TAG_MANAGER_ENVIRONMENT || '',
}, 'NauFooter');
});

subscribe(APP_CONFIG_INITIALIZED, async () => {
await hydrateAuthenticatedUser();
loadExternalScripts([GoogleTagManagerLoader], {
config: getConfig(),
});
});

const EVENT_NAMES = {
FOOTER_LINK: 'edx.bi.footer.link',
};
Expand Down Expand Up @@ -164,9 +180,5 @@ SiteFooter.defaultProps = {
supportedLanguages: [],
};

subscribe(APP_CONFIG_INITIALIZED, async () => {
await hydrateAuthenticatedUser();
});

export default injectIntl(SiteFooter);
export { EVENT_NAMES };
62 changes: 62 additions & 0 deletions src/services/gtmLoader.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/**
* @implements {GoogleTagManagerLoader}
* @memberof module:GoogleTagManager
*/
class GoogleTagManagerLoader {
constructor({ config }) {
this.gtmId = config.GOOGLE_TAG_MANAGER_ID;

this.gtmArgs = '';
if (config.GOOGLE_TAG_MANAGER_ENVIRONMENT) {
if (!config.GOOGLE_TAG_MANAGER_ENVIRONMENT.startsWith('&')) {
this.gtmArgs += '&';
}
this.gtmArgs += config.GOOGLE_TAG_MANAGER_ENVIRONMENT;
}
}

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

const noScriptSrc = document.createElement('noscript');

noScriptSrc.innerHTML = `
<iframe src="https://www.googletagmanager.com/ns.html?id=${key} height="0" width="0" style="display:none;visibility:hidden"></iframe>
`;
document.body.insertBefore(noScriptSrc, document.body.childNodes[0]);
};

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

export default GoogleTagManagerLoader;
Loading