Google tag manager Custom Template and Amplitude event logging

683 Views Asked by At

I'm trying to use the amazing features brought by the Custom Template on Google Tag Manager to organize the tags we use to log events on Amplitude.

I used to have a code like : amplitude.getInstance().logEvent(eventTitle, {args})

However, due to sandbox javascript we do not have direct access to amplitude.

So I tried to do:

const callInWindow = require('callInWindow');
const copyFromWindow = require('copyFromWindow');

const amplitude = copyFromWindow('amplitude');
callInWindow('amplitude.getInstance().logEvent', eventTitle, args);

And I gave full permissions on :

  • amplitude
  • amplitude.getInstance
  • amplitude.getInstance.logEvent

But the result is a tag failing with error saying : Tag XXX threw an error

The only workaround I found is to use a deprecated version of the API: amplitude.logEvent in the following way.

const callInWindow = require('callInWindow');
const copyFromWindow = require('copyFromWindow');

const amplitude = copyFromWindow('amplitude');
callInWindow('amplitude.logEvent', eventTitle, args);

And it works properly but I don't know for how long based on the deprecation announced by Amplitude : https://amplitude.github.io/Amplitude-JavaScript/Amplitude#amplitudelogevent

Does anyone know how I could in js sandbox first get the instance of amplitude.getInstance and then call used it's logEvent feature?

Your help would be highly appreciated.

Cheers!

1

There are 1 best solutions below

4
On

Does this code fix your issue?

const callInWindow = require('callInWindow');

const args = data.args.reduce((result, item) => {
  result[item.key] = item.value;
  return result;
}, {});

const amplitudeInstance = callInWindow('amplitude.getInstance');
amplitudeInstance.logEvent(data.eventTitle, args);

data.gtmOnSuccess();

You will need a text field called eventTitle and a table called args with key and value text columns for this code to work.

screenshot of fields

The template needed execute permissions for amplitude.getInstance, but that was all.