GTM custom pixel (Customer events)

YunusSoundboks
Shopify Partner
1 0 1

Hello Community!

We are currently migrating to the new checkout and we need to figure out how to install the GTM script as well as any other script that run in the checkout.

 

Script first: Is that even possible ? Say I have an Affirm script, or whatever.

 

GTM:
Using the webpixel didn't work. Window was not available. I tried following this guide: https://help.shopify.com/en/manual/promoting-marketing/pixels/custom-pixels/gtm-tutorial 

 

This is my code:

// Step 1. Initialize the JavaScript pixel SDK (make sure to exclude HTML)
(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;
  f.parentNode.insertBefore(j, f);
})(window, document, "script", "dataLayer", "GTM ID");
 
// Step 2. Subscribe to customer events with analytics.subscribe(), and add tracking
console.log("MELAD 1");
analytics.subscribe("page_viewed", (event) => {
  window.dataLayer.push({
    event: "page_viewed",
    id: event.id,
  });
});
 
When I get to checkout, window is not defined, which means the dataLayer is not defined.
Not sure what I'm doing wrong. The script is there, but dataLayer is not initialized.
 
Thanks in advance.
Reply 1 (1)

NicoSpoke
Shopify Partner
19 0 8

In our case we use Segment script. We also had an issue with "window not defined" so we had to wrap our code whenever we want to use the window. Perhaps try this:

if (window.dataLayer) {

 

window.dataLayer.push({
    event: "page_viewed",
    id: event.id,
  });

}

Building digital interfaces for Shopify Stores