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.
The virtual page view looks like this: ga('send', 'pageview', '/virtual/example1/');
I want GTM to search specifically on every page for just ga('send', 'pageview', '/virtual
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!");
}
}
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.