Partial page load is not being tracked by SPFx extension in google analytics

Copper Contributor

I am trying track SharePoint site usage in google analytics using SPFx extension. I am able to track full page load but not able to track partial page load which happens when we navigate from one site page to another from site navigation. And also when hit search in top navigation that also not being tracked.

Could any one please help me what is wrong.

Bellow is my code:

 

private CurrentLoadingPage = "";

private isThisInitialLoad = true;


private getCurrentPage(): string {
        return window.location.pathname + window.location.search;
}

private refreshCurrentPage(): void {
    this.CurrentLoadingPage = this.getCurrentPage();
}



private pageEvent(): void {
        let trackingID: string = this.properties.trackingID;
        if (!trackingID) {
          console.log('Id is missing');
        } else {
          Console.log(`id: ${trackingID}`);
          const currentPage = this.refreshCurrentPage();

  if (this.isThisInitialLoad) {

    this.freshPageLoad(trackingID);
    this.refreshCurrentPage();
    this.isThisInitialLoad = false;

  }
  else if (!this.isThisInitialLoad && (currentPage !== this.CurrentLoadingPage)) {
    this.partialPageLoad(trackingID);
    this.refreshCurrentPage();
  }
}


}



private freshPageLoad(trackingID: string): void {
var gtagScript = document.createElement("script");
gtagScript.type = "text/javascript";
gtagScript.src=`https://www.googletagmanager.com/gtag/js?id=${trackingID}`;
gtagScript.async = true;
document.head.appendChild(gtagScript);

eval(`
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
      gtag('config',  '${trackingID}');
    `);
}

private partialPageLoad(trackingID: string): void {
eval(`
    if(ga) {
      ga('create', '${trackingID}', 'auto');
      ga('set', 'page', '${this.getFreshCurrentPage()}');
      ga('send', 'pageview');
    }
    `);


}



@override
  public onInit(): Promise<void> {

    this.context.placeholderProvider.changedEvent.add(this, this.pageEvent);
    this.context.application.navigatedEvent.add(this, this.pageEvent);

return Promise.resolve();


 }
1 Reply

@Sarba995 

 

Try this

 

public onInit(): Promise<void> { 
	let trackingID: string = this.properties.trackingID; 
	if (!trackingID) 
	{ 
		Log.info( LOG_SOURCE, "Tracking ID not provided"; ); 
	}
	else 
	{ 
		var gtagScript = document.createElement("script"); 
		gtagScript.type = "text/javascript"; gtagScript.src=`https://www.googletagmanager.com/gtag/js?id=${trackingID}`; 
		gtagScript.async = true; document.head.appendChild(gtagScript); 
		eval(`window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config','${trackingID}'); `); 
	} 
	return Promise.resolve(); 
}