微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 跟踪Angular2中的Google Analytics网页浏览量

我使用Angular 2作为前端构建了一个站点.由于所有操作都是通过推送状态完成的,因此没有页面加载通常会触发Google Analytics代码页面视图发送到Google的服务器.

如何手动向Google发送网页浏览事件,以便跟踪我网站的哪些用户正在查看?

解决方法:

我设法通过订阅路由器上的更改,检查路由是否实际发生了变化(我有时在某些路由上获得了多个事件),然后将新路径发送给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')
        });
      }
    }
}

您还需要在加载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>

使用第三方库

作为自己实施GA的替代方案,库Angulartics2也是实现GA跟踪的流行工具,并且还与其他分析供应商集成.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐