0

Has anyone successfully added GA4 analytics to a Chrome Extension using the Measurement Protocol (gtag).

This post has the details for Universal Analytics, but has not been updated for GA4 which has a different protocol.

I have copied the exact code from the google instructions into the service worker (also validated by the Event Builder):

const measurement_id = `G-XXXXXXXXXX`;
const api_secret = `<secret_value>`;

fetch(`https://www.google-analytics.com/mp/collect?measurement_id=${measurement_id}&api_secret=${api_secret}`, {
  method: "POST",
  body: JSON.stringify({
    client_id: 'XXXXXXXXXX.YYYYYYYYYY',
    events: [{
      name: 'tutorial_begin',
      params: {},
    }]
  })
});

The extension console serves no errors, I just don't see any event data coming through to GA.

UPDATE

I managed to get it to work by moving the const values into the fetch url:

fetch(`https://www.google-analytics.com/mp/collect?measurement_id=G-XXXXXXXXXX&api_secret=secret_value`, {
  method: "POST",
  body: JSON.stringify({
    client_id: 'XXXXXXXXXX.YYYYYYYYYY',
    events: [{
      name: 'tutorial_begin',
      params: {},
    }]
  })
});
Miekshop
  • 1
  • 1
  • Add the API site to `host_permissions` and make the request in any extension script except content script. See also [Add google analytics into a chrome extension using manifest v3](https://stackoverflow.com/a/73825802) – wOxxOm Mar 01 '23 at 01:06
  • @wOxxOm I have already added this - it still doesn't work. That post is for UA and doesn't reflect the changes needed for GA4. I mentioned that in the post. – Miekshop Mar 01 '23 at 01:51
  • The answer I've linked is for GA4 Measurement Protocol. What do you see in [devtools -> Network inspector](/a/10258029) for the request? Also, AFAIK, you can't have URL parameters when using POST so maybe that example is incorrect despite being official. – wOxxOm Mar 01 '23 at 02:26
  • @wOxxOm the taxonomy used in that answer is the UA taxonomy. GA4 has a different structure. I don't know exactly what to look for in the network console but the fetch request is showing a status of 204 and no errors? Maybe the query parameters are where its breaking? – Miekshop Mar 01 '23 at 03:33

0 Answers0