在GTM中使用JS/jQuery查找特定的脚本行 [英] Find a specific line of script using JS/jQuery in GTM

查看:105
本文介绍了在GTM中使用JS/jQuery查找特定的脚本行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Google跟踪代码管理器(GTM)来确定是否在Google Analytics(分析)(GA)脚本(位于<head>中)中设置了虚拟页面视图.无法通过GTM设置GA代码.

I want to use Google Tag Manager (GTM) to identify if a virtual page view has been set within the Google Analytics (GA) script (which sits in the <head>). The GA code is NOT set via GTM.

虚拟页面视图如下:ga('send', 'pageview', '/virtual/example1/');

我希望GTM在每个页面上专门搜索ga('send', 'pageview', '/virtual

I want GTM to search specifically on every page for just ga('send', 'pageview', '/virtual

是否有一行JS或jQuery可用于识别这一行.像getElementById()之类的东西不起作用,因为没有ID.假设它可能在某个阶段使用innerHTML,但不确定将其组合在一起会很热.

Is there a line of JS or jQuery I can use to identify this line. Things like getElementById() don't work because there is no ID. Assume it might use innerHTML at some stage but not sure hot to put it all together.

推荐答案

从我的头顶来看,应该是这样的(可能需要一些改进,但原理是一样的):

From the top of my head it should be something like this (might need a little refinement, but the principle is as sound as these things get):

search = "ga('send', 'pageview', '/virtual/example1/');";
var scripts = document.getElementsByTagName("script");
for (var i=0, l=scripts.length; i<l; ++i ) { 
if(scripts[i].src.length > 0) continue;
  if ( scripts[i].innerHTML.indexOf(search) != -1 ) {
    alert("yay, virtual pageview!");
  }
}

搜索"变量包含您要查找的字符串. 脚本"变量获取页面上的所有脚本标签.循环将评估当前脚本标签的innerHTML,除非它包含源属性(具有源属性的脚本标签不包含可以评估的内联脚本).如果"search"变量包含在已评估脚本标记的innerHTML中,则您可以执行任何操作(在我的情况下,这是一个警报,在GTM中,您可能希望将自定义事件推送到数据层).

The "search" variable contains the string you are looking for. The "scripts" variable gets all script tags on the page. A loop evaluates the innerHTML of the current script tag, unless it contains a source attribute (script tags with source attributes do not contain inline scripts that could be evaluated). If the "search" variable is contained within the innerHTML of the evaluated script tag you can do whatever you want to do (in my case it's an alert, within GTM you probably want to push a custom event to the data Layer).

这需要放入自定义HTML标记中,如果在页面加载时触发该标记,则只会检查GTM代码之前的标记.

This needs to go into a custom HTML tag, if this is fired on page load it will only examine tags that precede the GTM code.

这篇关于在GTM中使用JS/jQuery查找特定的脚本行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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