我想使用Google跟踪代码管理器(GTM)来确定是否已在Google Analytics(GA)脚本(位于<head>
)中设置了虚拟页面视图。 GA代码不是通过GTM设置的。
虚拟页面视图如下所示:ga('send', 'pageview', '/virtual/example1/');
我希望GTM专门针对ga('send', 'pageview', '/virtual
我可以用一行JS或jQuery来识别这一行。 getElementById()
之类的内容不起作用,因为没有ID。假设它可能在某个阶段使用innerHTML
但不确定是否将它们放在一起。
答案 0 :(得分:0)
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!");
}
}
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).
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.