Skip to content

Instantly share code, notes, and snippets.

@cwparsons
Last active October 11, 2018 15:26
Show Gist options
  • Save cwparsons/694b1c24c6313f6e3f177b2ea087fa9f to your computer and use it in GitHub Desktop.
Save cwparsons/694b1c24c6313f6e3f177b2ea087fa9f to your computer and use it in GitHub Desktop.
/**
* Add an event callback when pushing events to Google Tag Manager's datalayer.
* Also provides a fallback if Google Tag Manager is not available.
* @see https://www.simoahava.com/gtm-tips/use-eventtimeout-eventcallback/
*/
const GTM_CONTAINER_ID = 'GTM-XXXXX';
export default function dataLayerPush(
eventObject: { [key: string]: string | number },
eventCallback?: () => void,
eventTimeout = 2000
) {
if (window['google_tag_manager']) {
const dataLayerEvent = {
...eventObject
} as any;
if (eventCallback) {
dataLayerEvent.eventCallback = (containerId: string) => {
/**
* eventCallback is run for every container on the page. To only apply the callback once,
* we check the container ID to only apply the callback for the one container.
* @see https://www.simoahava.com/analytics/check-container-id-with-eventcallback/
*/
if (containerId === GTM_CONTAINER_ID) {
eventCallback();
}
};
dataLayerEvent.eventTimeout = eventTimeout;
}
console.log(`Pushing event '${dataLayerEvent.event}' to Google Tag Manager.`);
window.dataLayer.push(dataLayerEvent);
} else if (eventCallback) {
console.log(`Google Tag Manager is not found on the page. Skipping ${eventObject.event}.`);
eventCallback();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment