I am working with angular v12 to build a web page that will be user with different clients, and i can tell the difference between clients based on a query param (realm) which is unique per client, and based on this realm param i get data from back end like custom font colors, users, etc...
Now i want to collect information for users that access only a specific page of the website via google analytics, but these information is not gathered by me, each client can insert his measurement id for his google analytics website and then information for users coming to there realms are gathered by them.
I have a question regarding this, first one is that i tried loading the gtag.js
script dynamically from within the component and get the measurement id specifically for that realm, but was faced with some issues like analytics is not able to link the data stream to the web page, (i think its something cause its not finding it in the index.html
like when adding meta tags for SEO - correct me if i am wrong -)
This is analytics.service.ts
:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AnalyticsService {
private isLoaded = false;
constructor() {}
loadGoogleAnalytics(measurementId: string): void {
console.log('hi loadGoogleAnalytics', measurementId);
if (!measurementId || this.isLoaded) {
return;
}
this.isLoaded = true;
// Create script tag
const script = document.createElement('script');
script.async = true;
script.src = `https://www.googletagmanager.com/gtag/js?id=${measurementId}`;
document.head.appendChild(script);
// Initialize GA
script.onload = () => {
(window as any).dataLayer = (window as any).dataLayer || [];
function gtag(...args: any[]) {
(window as any).dataLayer.push(args);
}
(window as any).gtag = gtag;
gtag('js', new Date());
gtag('config', measurementId);
this.trackPageView();
};
}
trackPageView(): void {
console.log('Tracking page view:', window.location.hash);
if ((window as any).gtag) {
(window as any).gtag('event', 'page_view', {page_title: document.title, page_path: window.location.hash });
}
}
}
so what is a suggested solution to solve this issue?
So the Problem was with how the gtag
method is being defined, it should match the gtag
method within gtag.js in order to work, so i add the script to index.html
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
</script>
and edited the analytics service:
loadGoogleAnalytics(measurementId: string): void {
if (!measurementId || this.isLoaded) {
return;
}
this.isLoaded = true;
// Create script tag
const script = document.createElement('script');
script.async = true;
script.src = `https://www.googletagmanager.com/gtag/js?id=${measurementId}`;
// Initialize GA
script.onload = () => {
(window as any).gtag('js', new Date());
(window as any).gtag('config', measurementId);
};
document.head.insertBefore(script, document.head.firstChild);
}
Also make sure to turn off any ad blocker extensions!