'Google Analytics 4: how to get the name of global object (gtag)
In Google Analytics Classic/Universal Analytics we could get the name of global object using such code:
window['GoogleAnalyticsObject']
And then we could get the object by its name:
window[window['GoogleAnalyticsObject']]
Looks like in GA4 such approach is not working, I am getting undefined if I try to get this name. Is it possible somehow to get this name in GA4 ?
Also this is my use case: I have a site on which GA4 was added, there is a possibility that the global object - gtag was renamed (but I don't know about that), theafore I need to get current name of the object and then to get the object by its name.
Solution 1:[1]
Per the updated Google Analytics 4 site tag documentation, it appears that object may now be in window.dataLayer
. I'm thinking either:
window[window.dataLayer['GoogleAnalyticsObject']]
or
window.dataLayer['GoogleAnalyticsObject']
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jeremy Caney |