Ian*_*her 43 javascript google-analytics angular
我使用Angular 2作为前端构建了一个新站点.由于所有操作都是通过推送状态完成的,因此没有页面加载通常会触发Google Analytics代码将页面视图发送到Google的服务器.
如何手动向Google发送网页浏览事件,以便跟踪我网站的哪些用户正在查看?
Ian*_*her 53
我设法通过订阅路由器上的更改,检查路由是否实际发生了变化(我有时在某些路由上获得了多个事件),然后将新路径发送给Google.
app.component.ts
import { ... } from '...';
// Declare ga function as ambient
declare var ga:Function;
@Component({ ... })
export class AppComponent {
private currentRoute:string;
constructor(_router:Router) {
// Using Rx's built in `distinctUntilChanged ` feature to handle url change c/o @dloomb's answer
router.events.distinctUntilChanged((previous: any, current: any) => {
// Subscribe to any `NavigationEnd` events where the url has changed
if(current instanceof NavigationEnd) {
return previous.url === current.url;
}
return true;
}).subscribe((x: any) => {
ga('set', 'page', x.url);
ga('send', 'pageview')
});
}
}
}
Run Code Online (Sandbox Code Playgroud)
您还需要在加载angular2应用程序之前在主索引文件中包含Google Analytics代码,以便全局ga对象存在,但您不希望两次发送初始视图.为此,请从GA脚本中删除以下行
的index.html
<script>
(function(i,s,o,g,r,a,m){...})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXX-X', 'auto');
// Remove this line to avoid sending the first page view twice.
//ga('send', 'pageview');
</script>
<!--
Load your ng2 app after ga.
This style of deferred script loading doesn't guarantee this will happen
but you can use Promise's or what works for your particular project.
-->
<script defer type="text/javascript" src="/app.js"></script>
Run Code Online (Sandbox Code Playgroud)
使用第三方库
作为自己实施GA的替代方案,Angulartics2库也是实现GA跟踪的流行工具,也可以与其他分析供应商集成.
dlo*_*omb 33
扩展伊恩的答案.您可以使用Rx的内置功能来处理当前路由和新路由之间的区别.
import { NavigationEnd, Router } from '@angular/router';
declare var ga: any;
export class AppComponent {
constructor(public router: Router) {
router.events.distinctUntilChanged((previous: any, current: any) => {
if(current instanceof NavigationEnd) {
return previous.url === current.url;
}
return true;
}).subscribe((x: any) => {
console.log('router.change', x);
ga('send', 'pageview', x.url);
});
}
}
Run Code Online (Sandbox Code Playgroud)
我们使用distinctUntilChanged运算符使观察者只发出NavigationEnd类型的项,并且没有与先前发出的项相同的路由.
nyx*_*yxz 21
如果您在2017年8月之后遇到此问题,那么您很可能应该使用gtag.js(Google Universal Analytics全球网站代码)而不是旧的analytics.js.我建议你在继续之前检查migrate from analytics.js和gtag.js页面之间的差异,以及gtag.js如何在单页面应用程序中工作.
当您从Google Analytics获取代码段时,它看起来像这样:
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=<%= GOOGLE_ANALYTICS_ID %>"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '<%= GOOGLE_ANALYTICS_ID %>'); <!-- Remove that one -->
</script>
Run Code Online (Sandbox Code Playgroud)
您需要删除脚本的最后一行并将其余部分添加到您的脚本中index.html.
然后,您必须将从上面的脚本中删除的行添加到您的代码中,并将该页面添加到跟踪中.基本上它与上面提到的那些人差不多,analytics.js但是现在你使用了这个gtag.js功能.
例如,如果要跟踪您在此处打开的所有页面,请参阅示例代码:
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import 'rxjs/add/operator/distinctUntilChanged';
// This still has to be declared
declare var gtag: Function;
@Component({
moduleId: module.id,
selector: 'my-app',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css'],
})
export class AppComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
this.router.events.distinctUntilChanged((previous: any, current: any) => {
// Subscribe to any `NavigationEnd` events where the url has changed
if(current instanceof NavigationEnd) {
return previous.url === current.url;
}
return true;
}).subscribe((x: any) => {
gtag('config', '<%= GOOGLE_ANALYTICS_ID %>', {'page_path': x.url});
});
}
}
Run Code Online (Sandbox Code Playgroud)
如果您已经阅读了gtag.js当时的文档,那么您知道可能有大量的跟踪选项,但我会关注这里最基本的用法.
在 Angular 6 中,我建议使用 app.component.ts:
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router'
import { Title } from '@angular/platform-browser';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(
private router: Router,
private titleService: Title
){ }
ngOnInit() {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
(<any>window).gtag('config', '<%= GOOGLE_ANALYTICS_ID %>', {
'page_title' : this.titleService.getTitle(),
'page_path': event.urlAfterRedirects
});
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
对于 index.html :
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=<%= GOOGLE_ANALYTICS_ID %>"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
</script>
Run Code Online (Sandbox Code Playgroud)
您可以使用 Angular 提供的 Title 服务来管理页面的标题:https : //angular.io/guide/set-document-title
| 归档时间: |
|
| 查看次数: |
20628 次 |
| 最近记录: |