Find a specific line of script using JS/jQuery in GTM

好久不见. 提交于 2019-12-20 07:46:02

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/31678960/find-a-specific-line-of-script-using-js-jquery-in-gtm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!