April 27, 2020
Estimated Post Reading Time ~

How to include dynamic custom script to websites through GTM(Google Tag Manager)

Google Tag Manager is a tag management system that allows you to quickly and easily update tracking codes and related code fragments collectively known as "tags" on your website or mobile app. Once a small segment of Tag Manager code has been added to your project, you can easily configure and deploy your tag configurations from a web-based user interface without the need to deploy additional code in most cases. This reduces errors and frees you from having to involve a developer every time you need to make changes.

This post explains the approach to use Google Tag Manager(GTM) to include the dynamic scripts as part of Adobe Experience Manager(AEM) websites.

Create a free google tag manager account if one is not available


Install the GTM header and body scripts to the AEM website




Copy the head script to the header file and body script to body footer(start of body section)








Define new tag:


Select the Tag Configuration as Custom HTML and enter the name for tag


Enter the required custom script into the tag configuration - script file or the script text can be added(while adding the script text, please note the special characters should be escaped)


<script>
var s = document.createElement("script");
s.innerHTML = "alert('Custom Script from GTM');"; // add the custom script content
//s.src="test.js";// specify the script file instead of script content
document.head.appendChild(s);
</script>

Adding multi line script - example
s.innerHTML = "document.onreadystatechange = function(){ "+
"if(document.readyState=='loaded' || document.readyState=='complete') "+
"alert('test');"+
"}";


Add Trigger


Select All Pages(Configure the trigger based on the requirement)


Select the tag firing option under Advanced Settings as Once per Page


Save the configuration

Preview the configurations:


The GTM Debugger displays the tags details on preview mode.




Now the script is included in the website




Publish the tag after successful testing




By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.