带有 AngularJS 的 Google 标签管理器? [英] Google Tag Manager with AngularJS?

查看:22
本文介绍了带有 AngularJS 的 Google 标签管理器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Angular 中使用 GTM?

How do I use GTM with Angular?

当我使用以下代码加载新的部分时,我试图触发(虚拟)页面浏览事件:

I'm trying to fire a (virtual) pageview event when I load a new partial using this code:

dataLayer.push({
    'event' : 'pageview',
    'pageview' : $location.path(),
    'virtualUrl' : $location.path()
 });

但我没有看到事件触发(我使用 Google Analytics Chrome 调试扩展程序查看触发的事件).

But I don't see the event firing (I'm using the Google Analytics Chrome debug extension to view fired events).

推荐答案

我发现 Chrome 扩展程序不可靠.只需在控制台中运行全局变量 dataLayer 即可打印事件数组.其中一个对象应该是您的网页浏览事件.

I find the Chrome extension unreliable. Simply run the global variable dataLayer in the console to print the array of events. One of the objects should be your pageview event.

以下是我们如何使用它的示例:

Here is an example of how we are using it:

注意:我们不是简单地使用 $location.path(),而是使用域名之后的 url 中的所有内容.其中包括 .search() &.hash().

Note: we're not simply using $location.path(), instead everything in the url after the domain. Which includes the .search() & .hash().

Angular 文档中的 $location

(function(window, angular) {
    'use strict';
    angular.module('Analytic.module', ['Analytic.services']).
        run(function($rootScope, $window, $location, GoogleTagManager) {
            $rootScope.$on('$viewContentLoaded', function() {
                var path= $location.path(),
                    absUrl = $location.absUrl(),
                    virtualUrl = absUrl.substring(absUrl.indexOf(path));
                GoogleTagManager.push({ event: 'virtualPageView', virtualUrl: virtualUrl });
            });
        });
})(window, window.angular);

服务/analytic.js

(function() {
    angular.module('Analytic.services', []).
        service('GoogleTagManager', function($window) {
            this.push = function(data) {
                try {
                    $window.dataLayer.push(data);
                } catch (e) {}
            };
        });
})();

在 GTM 中

您需要 {{virtualUrl}}{{event}} 宏来监听同名的 dataLayer 变量.

In GTM

You'll need {{virtualUrl}} and {{event}} Macros which listen for the dataLayer variables of the same name.

您需要一个带有触发规则的 Google Analytics 事件跟踪标记,该标记在 {{event}} 等于virtualPageView"时触发.确保删除默认的所有页面"规则,该规则使其在每次页面加载时运行.相反,您希望它在您 dataLayer.push() 事件时运行,这可能在每次页面刷新时发生多次.

You'll need a Google Analytics Event Tracking Tag with a Firing Rule which triggers when {{event}} equals 'virtualPageView'. Make sure you remove the default 'All Pages' Rule which makes it run on every page load. Instead, you want it to run when you dataLayer.push() the event, which may happen multiple times per page refresh.

标签应配置为:

  1. 跟踪类型 == '页面浏览'
  2. 更多设置 > 基本配置 > 虚拟页面路径 == '{{virtualUrl}}'

这篇关于带有 AngularJS 的 Google 标签管理器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆