1

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 });
    }
  }  
}

google analytics test tag

so what is a suggested solution to solve this issue?

2
  • try this answer maybe it helps Commented Feb 19 at 8:45
  • i am already adding the code in onload() function
    – Kardon63
    Commented Feb 19 at 9:51

2 Answers 2

1

There should be no problem loading gtag from a component regardless of the framework as long as it looks properly in the DOM. No, gtag wouldn't care if there's no index.html. Why would it? It's a front-end script running in the browser. You could load and invoke it from the console on virtually any site.

Seems to me like you could use a few more debugging steps.

  • SO uses gtag. Open the DOM here, see how gtag is loaded there. Make sure yours looks similar.
  • Make sure you're using the correct measurement id. Measurement id is exactly how GA links data to a data stream.
  • Open the network tab, see that your page indeed loads the gtag and make sure you see events dispatching to Google's collect endpoint. You can check the measurement id in the network calls too, but normally it's whatever's in the DOM.
1
  • thanks for the answer, i'll close the question cause it was a problem with the definition of gtag(...args: any[]) it should be without the args, also i was facing ad blocker problems so the script was not downloading
    – Kardon63
    Commented Feb 20 at 10:22
0

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!

Not the answer you're looking for? Browse other questions tagged or ask your own question.