diff --git a/integrations/GoogleTagManager/browser.js b/integrations/GoogleTagManager/browser.js new file mode 100644 index 000000000..bd4bd5c35 --- /dev/null +++ b/integrations/GoogleTagManager/browser.js @@ -0,0 +1,77 @@ +import logger from "../../utils/logUtil"; +class GoogleTagManager { + constructor(config) { + this.containerID = config.containerID; + this.name = "GOOGLETAGMANAGER"; + } + + init() { + logger.debug("===in init GoogleTagManager==="); + (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; + f.parentNode.insertBefore(j, f); + })(window, document, "script", "dataLayer", this.containerID); + } + + identify(rudderElement) { + logger.error("method not supported"); + } + + track(rudderElement) { + logger.debug("===in track GoogleTagManager==="); + let rudderMessage = rudderElement.message; + let props = { + event: rudderMessage.event, + userId: rudderMessage.userId, + anonymousId: rudderMessage.anonymousId, + ...rudderMessage.properties + }; + this.sendToGTMDatalayer(props); + } + + page(rudderElement) { + logger.debug("===in page GoogleTagManager==="); + let rudderMessage = rudderElement.message; + let pageName = rudderMessage.name; + let pageCategory = rudderMessage.properties + ? rudderMessage.properties.category + : undefined; + + let eventName; + + if (pageName) { + eventName = "Viewed " + pageName + " page"; + } + + if (pageCategory && pageName) { + eventName = "Viewed " + pageCategory + " " + pageName + " page"; + } + + let props = { + event: eventName, + userId: rudderMessage.userId, + anonymousId: rudderMessage.anonymousId, + ...rudderMessage.properties + }; + + this.sendToGTMDatalayer(props); + } + + isLoaded() { + return !!( + window.dataLayer && Array.prototype.push !== window.dataLayer.push + ); + } + + sendToGTMDatalayer(props) { + window.dataLayer.push(props); + } +} + +export { GoogleTagManager }; diff --git a/integrations/GoogleTagManager/index.js b/integrations/GoogleTagManager/index.js new file mode 100644 index 000000000..c3f148dad --- /dev/null +++ b/integrations/GoogleTagManager/index.js @@ -0,0 +1,3 @@ +import { GoogleTagManager } from "./browser"; + +export default GoogleTagManager; diff --git a/integrations/index.js b/integrations/index.js index c8017ac7e..53bd2194d 100644 --- a/integrations/index.js +++ b/integrations/index.js @@ -3,13 +3,15 @@ import * as GA from "./GA"; import * as Hotjar from "./Hotjar"; import * as GoogleAds from "./GoogleAds"; import * as VWO from "./VWO"; +import * as GoogleTagManager from "./GoogleTagManager"; let integrations = { HS: HubSpot.default, GA: GA.default, HOTJAR: Hotjar.default, GOOGLEADS: GoogleAds.default, - VWO: VWO.default + VWO: VWO.default, + GTM: GoogleTagManager.default }; export { integrations };