Why doesn't Google Analytics send hits when my app is loaded in a cross-domain iframe?
Asked Answered
F

1

8

I have a basic static / single page app I added Google Analytics 4 (GA4) to using gtag. Page views are tracked as expected when I load my app locally via http://localhost:8080. However, when I embed by app on another site in an iframe, no hits are sent.

To debug this, I've looked at the network requests in the Chrome network inspector. When I open my app directly at http://localhost:8080, I can see a request to https://analytics.google.com/g/collect?... in the network requests. However, when I load my app in an iframe (e.g. I add <iframe src="http://localhost:8080"></iframe> to another page), I notice that this request isn't sent. I've also confirmed that no data shows up in Google Analytics in the Realtime view even though I can see the JavaScript for gtag loading.

I've also debugged by using the Tag Assistant at https://tagassistant.google.com/. Even when I connect to my app running in the iframe, the debugger shows that all events are registered as expected, but under hits sent, it says "No hits were sent by this container".

Why would the behavior of the same tracking code behave any differently when the app is loaded in an iframe? How do I ensure that hits are sent all the time?

Update: This appears to be related to cookies not being available within the cross-domain iframe, but is there a workaround?

Flageolet answered 13/1, 2021 at 4:13 Comment(1)
I’m voting to close this question because its not programming related may be better suited for webapps.stackexchange.com or webmasters.stackexchange.comErective
F
7

By default, tracking fails due to SameSite cookie setting enforcement. By default, cookies aren't available in a third-party context, and this includes and iframe that's included from a different domain.

By using the cookie_flags config (docs), you can allow cookies to be read from a third-party context. There will be some caveats and this will vary by browser, as privacy restrictions keep increasing.

However, for now, setting cookie_flags in the gtag config fixes the issue as long as your site is secure:

gtag('config', '<MEASUREMENT_ID>', {
  cookie_flags: 'SameSite=None;Secure'
})

Note that this won't actually work with http://localhost:8080 since it's not secure, but once the site is deployed to production, hopefully you'll be using https.

Flageolet answered 13/1, 2021 at 18:59 Comment(1)
Thanks a lot. I was stuck on this issue for a long time. This issue occurs only on chrome. They should mention this in their docs.Blackbeard

© 2022 - 2024 — McMap. All rights reserved.