Vitalii Oliinyk
Vitalii Oliinyk

Reputation: 31

Is there a way to track time user spent on page using Google analytics (Angular)

I have an Angular application and I want to track time user spent on each page using google analytics. What is the best way to do it? (Or maybe there are alternatives to Google Analytics that have this functionality out of the box?)

Upvotes: 0

Views: 825

Answers (1)

Berk Kurkcuoglu
Berk Kurkcuoglu

Reputation: 1523

As Angular is an SPA, you need to set the page manually on Google Analytics. In order to do that you have set a listener on route changes.

Something similar to this is required:

 private subscribeToRouteChanges(): void {
    this.router.events
      .pipe(filter(event => event instanceof NavigationEnd))
      .subscribe((event: NavigationEnd) => this.sendPageDataToGoogleAnalytics(event.urlAfterRedirects));
  }

  public sendPageDataToGoogleAnalytics(url: string): void {
   //need a title for each page which will be shown at GA dashboards 
   //you can setup your own service or static function to return a title for each route registered
    const pageTitle = this.pageTitleService.getPageTitle(url);   
    if (pageTitle) {
      (window as any).ga('set', 'page', url);
      (window as any).ga('set', 'title', pageTitle);
      (window as any).ga('send', 'pageview');
    }
  }

Upvotes: 2

Related Questions