@@ -43,6 +43,7 @@ export default class GA4 {
4343 removeTrailingSlashes ( config . sdkBaseUrl ) || 'https://www.googletagmanager.com' ;
4444 this . serverContainerUrl = config . serverContainerUrl || null ;
4545 this . isExtendedGa4_V2 = config . isExtendedGa4_V2 || false ;
46+ this . gtagLoadedAt = null ;
4647 ( {
4748 shouldApplyDeviceModeTransformation : this . shouldApplyDeviceModeTransformation ,
4849 propagateEventsUntransformedOnError : this . propagateEventsUntransformedOnError ,
@@ -128,12 +129,20 @@ export default class GA4 {
128129 * Setting the parameter sessionId, clientId and session_number using gtag api
129130 * Ref: https://developers.google.com/tag-platform/gtagjs/reference
130131 */
131- window . gtag ( 'get' , this . measurementId , 'session_id' , sessionId => {
132- this . sessionId = sessionId ;
133- } ) ;
134- window . gtag ( 'get' , this . measurementId , 'client_id' , clientId => {
135- this . clientId = clientId ;
136- } ) ;
132+ if ( ! this . overrideClientAndSessionId ) {
133+ window . gtag ( 'get' , this . measurementId , 'session_id' , sessionId => {
134+ this . sessionId = sessionId ;
135+ } ) ;
136+ } else {
137+ this . sessionId = this . analytics . getSessionId ( ) ;
138+ }
139+ if ( ! this . overrideClientAndSessionId ) {
140+ window . gtag ( 'get' , this . measurementId , 'client_id' , clientId => {
141+ this . clientId = clientId ;
142+ } ) ;
143+ } else {
144+ this . clientId = this . analytics . getAnonymousId ( ) ;
145+ }
137146 window . gtag ( 'get' , this . measurementId , 'session_number' , sessionNumber => {
138147 this . sessionNumber = sessionNumber ;
139148 } ) ;
@@ -146,10 +155,19 @@ export default class GA4 {
146155 }
147156
148157 /**
149- * If the gtag is successfully initialized, client ID and session ID fields will have valid values for the given GA4 configuration
158+ * If the gtag is successfully initialized, client ID and session ID fields will have valid values for the given GA4 configuration.
159+ * Returns true only after 2 seconds from init() to allow gtag to fully initialize.
150160 */
151161 isLoaded ( ) {
152- return ! ! ( this . sessionId && this . clientId ) ;
162+ const LOAD_DELAY_MS = 2000 ;
163+ const gtagReady = ! ! ( window . dataLayer && window . dataLayer . push !== Array . prototype . push ) ;
164+ if ( gtagReady && this . getLoadedAt === null ) {
165+ this . gtagLoadedAt = Date . now ( ) ;
166+ }
167+ const hasWaitedLongEnough =
168+ this . gtagLoadedAt !== null && Date . now ( ) - this . gtagLoadedAt >= LOAD_DELAY_MS ;
169+ const hasValidSession = this . sessionNumber !== null ;
170+ return gtagReady && ( hasValidSession || hasWaitedLongEnough ) ;
153171 }
154172
155173 isReady ( ) {
0 commit comments