Amplitude and GTM integration

Viewed 108

Trying to add GA's client ID to Amplitude's User property. Once the page is loaded, an visit page event is triggered. As used GTM script is still not loaded, a new client (visitor) won't have assigned the client ID. This is the problem I'm trying to fix.

My initial "solution" is based on storing the tracking events to a queue till client ID is received. The second part is "handshaking" - the app is puling until the client ID is loaded or a timeout is happened.

The "brutal force" implementation of handshake between GA and Amp didn't work. GTM loader is modified as (j.onload is added):

`a(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.onload=function() {window.gaLoaded?.()};...`

so once the script is loaded, a global fn gaLoaded is called.

The pulling function is:

window.gaLoaded = () => {
    let count = 50 // 5 sec and we will go wo GA client id
    clearTimeout(timerId)
    function setGaClientId() {
      count -= 1
      if (count < 0) {
        isWaitingForClientId = false
        flushTrackQueue()
        return
      }
      // wait till gtm is initialized - ga function will be injected to window object
      if (typeof window.ga === 'function') {
        // https://developers.google.com/analytics/devguides/collection/analyticsjs/cookies-user-id#getClientId
        const clientId = window.ga?.getAll?.()[0].get(GTM_CLIENT_ID)
        if (!clientId) {
          setTimeout(setGaClientId, 100)
          return
        }

        const identifyObj = new Identify()
        identifyObj.set('GAclientId', clientId)
        identify(identifyObj)
        isWaitingForClientId = false
        flushTrackQueue()
      } else {
        setTimeout(setGaClientId, 100)
      }
    }
    if (isWaitingForClientId) {
      setGaClientId()
    }
  }
  window.gaLoaded(); // GA might be loaded before this script is executed so check for the GA's client id

Please could you share your experience on this topic?

0 Answers
Related