Hi, I found there was two ways to do this, not sure either is the optimal but both get the GTM tags directly after the body tags.
-
Add the script to the "body" params text area in the master page template. I close off the body tag with a ">" then paste in the GTM script and I remove the last ">" tags from the script as it will be replaced by the existing Master page body code. Should look like this at the start ><!-- Google Tag Manager -->Your script GTM goes here
and this at the end <!-- End Google Tag Manager --
.
-
I had an issue because I had sub-domains all using their own Google ID so I went with adapting the PortalTemplate.aspx page using a Literal tag plus some code behind.
For the .aspx page I used:
<body class="<%=BodyClass%>" <%=BodyParameters%>>
<asp:Literal runat="server" ID="GTMTags" EnableViewState="false" />
<form id="form" runat="server">
For the code behind I used:
`protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
// Init the header tags
tags.Text = HeaderTags;
//insert Google GTM tags
GTMTags.Text = getGTMTags(CMS.CMSHelper.CMSContext.CurrentSiteID).ToString();
if (CMSContext.ViewMode == ViewModeEnum.Wireframe)
{
CSSHelper.RegisterWireframesMode(this);
}
}
protected String getGTMTags(int siteID)
{
StringBuilder gtmHTML = new StringBuilder();
int thisSite = siteID;
String SQGTMCode = "GTM-********"; // default id
switch (thisSite)
{
case 2:
SQGTMCode = "GTM-*******"; // main website
break;
case 5:
SQGTMCode = "GTM-&&&&&&&&"; // another sub domain
break;
case 8:
SQGTMCode = "GTM-@@@@@@@@"; // sub domain
break;
default:
SQGTMCode = "GTM-*******";
break;
}
gtmHTML.Append("<!-- Google Tag Manager --> ");
gtmHTML.Append("<noscript><iframe src=\"//www.googletagmanager.com/ns.html?id=" + SQGTMCode.ToString() + "\" height=\"0\" width=\"0\" style=\"display:none;visibility:hidden\"></iframe></noscript>");
gtmHTML.Append("<script>");
gtmHTML.Append("(function(w,d,s,l,i){w[l]=w[l]||[];");
gtmHTML.Append("w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});");
gtmHTML.Append("var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';");
gtmHTML.Append("j.async=true;j.src= '//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })");
gtmHTML.Append("(window,document,'script','dataLayer','" + SQGTMCode.ToString() + "');");
gtmHTML.Append("</script>");
gtmHTML.Append("<!-- End Google Tag Manager -->");
return gtmHTML.ToString();
}`
Like I said, it may not be the best way but it works, if anyone sees anything blatantly wrong with this code please let me know.