首页 文章

自动为Google代码管理器生成下载事件

提问于
浏览
2

我一直在尝试为谷歌标签管理器自动生成事件 .

我们有一个脚本,我们使用传统的异步分析,为下载,电子邮件和外部点击生成onclick事件 .

我将其修改为生成GTM事件而不是标准分析事件,如下所示:

if (typeof jQuery != 'undefined') {
    jQuery(document).ready(function($) {
        var filetypes = /\.(zip|exe|pdf|doc*|xls*|ppt*|mp3)$/i;
        var baseHref = '';
        if (jQuery('base').attr('href') != undefined)
            baseHref = jQuery('base').attr('href');
        jQuery('a').each(function() {
            var href = jQuery(this).attr('href');
            if (href && (href.match(/^https?\:/i)) && (!href.match(document.domain))) {
                jQuery(this).click(function() {
                    var extLink = href.replace(/^https?\:\/\//i, '');
                    dataLayer.push  ({'eventCategory' : 'External', 'eventAction' : 'click', 'eventLabel': extLink, 'event' : 'autoevent'});
                    if (jQuery(this).attr('target') != undefined && jQuery(this).attr('target').toLowerCase() != '_blank') {
                        setTimeout(function() { location.href = href; }, 200);
                        return false;
                }
            });
        }
        else if (href && href.match(/^mailto\:/i)) {
            jQuery(this).click(function() {
                var mailLink = href.replace(/^mailto\:/i, '');
                dataLayer.push({'eventCategory' : 'Email', 'eventAction' : 'click', 'eventLabel': mailLink, 'event' : 'autoevent'});
            });
        }
        else if (href && href.match(filetypes)) {
            jQuery(this).click(function() {
                var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
                var filePath = href;
                 dataLayer.push({'eventCategory' : 'Download', 'eventAction' : 'click', 'eventLabel': filePath', 'event' : 'autoevent'});
                if (jQuery(this).attr('target') != undefined && jQuery(this).attr('target').toLowerCase() != '_blank') {
                    setTimeout(function() { location.href = baseHref + href; }, 200);
                    return false;
                }
            });
        }
    });
});
}

在GTM内部,我会监听一个名为autoevent的事件,它会生成一个包含Category,Action和Label值的事件标记 .

到目前为止,我一直在尝试使用wordpress网站 .

我的第一次尝试在头部宣布了上述脚本 . 根据需要,GTM代码在正文中 .

在chrome中使用GA调试器,我收到一个JS错误Uncaught SyntaxError:发出dataLayer推送的行上的意外标识符 .

我的Javascript sux,所以我猜测并将dataLayer声明为GTM代码之上,并将自动生成脚本移动到GTM代码下方,以便完全声明dataLayer . 发生相同的错误 .

有什么建议?

1 回答

  • 0

    你在filePath上有一个额外的单引号:

    dataLayer.push({'eventCategory' : 'Download', 'eventAction' : 'click', 'eventLabel': filePath', 'event' : 'autoevent'});
    

相关问题