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

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

问题描述

我想使用 Google 跟踪代码管理器 (GTM) 来确定是否已在 Google Analytics (GA) 脚本(位于 中)中设置了虚拟页面浏览量.GA 代码不是通过 GTM 设置的.

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/');

The virtual page view looks like this: 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!");
  }
}

搜索"变量包含您要查找的字符串.scripts"变量获取页面上的所有脚本标签.循环评估当前脚本标签的innerHTML,除非它包含一个源属性(具有源属性的脚本标签不包含可以被评估的内联脚本).如果搜索"变量包含在评估脚本标签的 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天全站免登陆