How to jailbreak customer events in Shopify
What I've been thinking about
I’m an analytics bum. It’s probably what I like to do the most! You can bet I was excited when Shopify announced Customer Events. Finally! I thought. No more DOM scraping and finicky template hacks that need to be tweaked for every theme. I’ll be able to create one script to rule them all, I thought.
Eagerly, I went on the Customer Events page, set-up a GTM script on the “all_events” event just to test things out, plugged everything in excitedly and… nothing. Nothing was firing at all. I was pretty bummed, so I dived in the docs a bit further. Ah, I discovered, those cool events are sandboxed. No luck on getting an easy win there.
Not one to quit, I went deep in the rabbit hole, and tried a million ways to get those sweet sweet events out of their cage, each more hacky than the next. Then I stumbled on the holy grail: postMessage. It’s built specifically for communicating data between windows, sandboxed iframes being one of those use cases.
While this method is not officially supported by Shopify, it uses a well documented function, so it should be fairly safe to use.
Add this to theme.liquid and checkout additional scripts:
And create a custom pixel with this:
What's going to happen with this is that the complete event data for every customer event will be sent over as a JSON string, which will trigger a dataLayer.push event on the main window, that you can use however you'd like. You'll be able to set-up custom out of the customer event names, parse the data coming from customer events, etc.
This is the basic code that you should tweak for your needs. For example, you might need to structure the data according to GA4 schema. In that case, you could structure it within the Customer Events code block, to send a clean JSON object to catch on the main window. Or you could keep the "raw" object coming from Customer Events, and organize it on the main Window using GTM. It's your choice!
3 links you can't miss
- https://stape.io/ - Server side GTM on easy mode. Get an sGTM container running in minutes, at a cheaper price than using Google Cloud Platform. They even have a Shopify app to fire webhooks for purchases and refunds!
- Feedarmy - How to add Enhanced Conversions on Google Ads using gtag.js. This helps improve conversion tracking, which in theory improves the targeting algorithm for automated bid strategies.
- Simo Ahava - The ultimate guide to setting up GA4 using GTM. This is your bible if you want to use the code I shared above to create your own custom GA4 implementation!
One app I like
Sliderule Analytics. Want to get an awesome tracking set-up in a few clicks, for free? This is your solution. In my experience, it's better than the new native integration, available within the Google channel since early March. It will fit 95% of merchants analytics needs, using 5% of the effort.