Skip to content

Commit

Permalink
Merge pull request #321 from usnistgov/feature/ODD1091-ga4-fix
Browse files Browse the repository at this point in the history
Standardizing handling of navigation in SPA for GA4.
  • Loading branch information
RayPlante authored Dec 6, 2023
2 parents 1b87047 + 6b1d5e7 commit bfaba15
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 8 deletions.
61 changes: 58 additions & 3 deletions angular/src/app/app.component.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import { Component, AfterViewInit, OnInit, PLATFORM_ID, Inject } from '@angular/core';
import { Router, NavigationStart, NavigationEnd, NavigationCancel, NavigationError } from '@angular/router';
import { Router, NavigationStart, NavigationEnd, NavigationCancel, NavigationError, RouterState, ActivatedRoute } from '@angular/router';
import './content/modal.less';
import { GoogleAnalyticsService } from './shared/ga-service/google-analytics.service'
import { AppConfig } from './config/config';
import { isPlatformBrowser } from '@angular/common';
import { Title } from '@angular/platform-browser';
import { DOCUMENT } from '@angular/common';

declare const gtag: Function;

@Component({
selector: 'app-root',
Expand All @@ -15,10 +19,14 @@ export class AppComponent {
gaCode: string;
ga4Code: string = null;
inBrowser: boolean = false;
hostName: string = "dada.nist.gov";

constructor(private gaService: GoogleAnalyticsService,
private cfg: AppConfig,
@Inject(PLATFORM_ID) private platformId: Object)
@Inject(PLATFORM_ID) private platformId: Object,
public router: Router,
private titleService: Title,
@Inject(DOCUMENT) private document: Document)
{
this.inBrowser = isPlatformBrowser(platformId);
}
Expand All @@ -32,9 +40,56 @@ export class AppComponent {
if(this.inBrowser){
this.gaCode = this.cfg.get("gaCode", "") as string;
this.ga4Code = this.cfg.get("ga4Code", "") as string;
let homeurl = this.cfg.get("locations.portalBase", "data.nist.gov") as string;
console.log('homeurl', homeurl);
const url = new URL(homeurl);
this.hostName = url.hostname;


this.gaService.appendGaTrackingCode(this.gaCode, this.ga4Code, this.hostName);

//Add GA4 code to track page view
this.handleRouteEvents();

}
}

this.gaService.appendGaTrackingCode(this.gaCode, this.ga4Code);
/**
* GA4 code to track page view when user navigates to different pages
*/
handleRouteEvents() {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
const title = this.getTitle(this.router.routerState, this.router.routerState.root).join('-');
this.titleService.setTitle(title);

gtag('event', 'page_view', {
page_title: title,
page_path: event.urlAfterRedirects,
page_location: this.document.location.href,
cookie_domain: this.hostName,
cookie_flags: 'SameSite=None;Secure'
})
}
});
}

/**
* Get page title if any
* @param state router state
* @param parent Activated route
* @returns
*/
getTitle(state: RouterState, parent: ActivatedRoute): string[] {
const data = [];
if (parent && parent.snapshot.data && parent.snapshot.data['title']) {
data.push(parent.snapshot.data['title']);
}
if (state && parent && parent.firstChild) {
data.push(...this.getTitle(state, parent.firstChild));
}
return data;
}

}

7 changes: 2 additions & 5 deletions angular/src/app/shared/ga-service/google-analytics.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,12 @@ export class GoogleAnalyticsService {
* This function takes GA tracking code as a parameter, constructs the script
* and adds it to the top of current page.
*/
public appendGaTrackingCode(gaCode: string, ga4Code: string) {
public appendGaTrackingCode(gaCode: string, ga4Code: string, hostname: string = "dada.nist.gov") {
try {
//GA3
let scriptId = '_fed_an_ua_tag';

if (document.getElementById(scriptId)) {
console.log("Found GA id.");
document.getElementById(scriptId).remove();
}

Expand All @@ -79,7 +78,6 @@ export class GoogleAnalyticsService {
scriptId = '_gtag_js';

if (document.getElementById(scriptId)) {
console.log("Found GA id.");
document.getElementById(scriptId).remove();
}

Expand All @@ -95,14 +93,13 @@ export class GoogleAnalyticsService {
scriptId = '_dataLayer';

if (document.getElementById(scriptId)) {
console.log("Found GA id.");
document.getElementById(scriptId).remove();
}

var s2 = document.createElement('script') as any;
s2.type = "text/javascript";
s2.id = scriptId;
s2.text = "window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '" + ga4Code+ "');";
s2.text = "window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '" + ga4Code+ "',{'cookie_domain':'"+ hostname + "','cookie_flags': 'SameSite=None;Secure'})";

var h2 = document.getElementsByTagName("head");
document.getElementsByTagName("head")[0].appendChild(s2);
Expand Down

0 comments on commit bfaba15

Please sign in to comment.