最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Load GA4 script from specific component in angular - Stack Overflow

programmeradmin6浏览0评论

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 = `=${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?

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/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?

Share Improve this question asked 20 hours ago Kardon63Kardon63 3461 gold badge6 silver badges21 bronze badges 2
  • try this answer maybe it helps – Naren Murali Commented 19 hours ago
  • i am already adding the code in onload() function – Kardon63 Commented 18 hours ago
Add a comment  | 

1 Answer 1

Reset to default 0

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.
发布评论

评论列表(0)

  1. 暂无评论