Skip to content

Instantly share code, notes, and snippets.

@tomstorms
Last active March 26, 2022 22:53
Show Gist options
  • Save tomstorms/bddce76dc473ccdde99d2a78763ea882 to your computer and use it in GitHub Desktop.
Save tomstorms/bddce76dc473ccdde99d2a78763ea882 to your computer and use it in GitHub Desktop.
#-----------------------------------------------------
# Get Client IP
#
# You can find a list of other IP services here: https://stackoverflow.com/questions/391979/how-to-get-clients-ip-address-using-javascript
#
# - Create a Custom Javascript Variable in GTM
#
function () {
if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET","//api.hostip.info/get_html.php",false);
xmlhttp.send();
hostipInfo = xmlhttp.responseText.split("\n");
for (i=0; hostipInfo.length >= i; i++) {
ipAddress = hostipInfo[i].split(":");
if (ipAddress[0] == "IP") return ipAddress[1].trim();
}
return false;
}
#-----------------------------------------------------
# Using GTM Variables in Tags
#
<script>
...
var pageUrl = {{Page URL}}; // use from GTM Variables
...
</script>
#-----------------------------------------------------
# Custom Function to generate SHA256 Hashes
#
// Create as a Tag
<script>
(function() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/js-sha256/0.9.0/sha256.min.js';
script.setAttribute('integrity','sha384-2epjwyVj8M4n8AweIsY7SKPSJmqBBBkmksXvkmtYORfxPS1I4NZE/+Ttk/9gCELG');
script.setAttribute('crossorigin','anonymous');
document.getElementsByTagName('head')[0].appendChild(script);
})();
</script>
// You can then reference to it in a Custom Javascript variable like this:
function() {
var name = "Tom";
var hashName = sha256(name);
// Do something with hashName
return true
}
#-----------------------------------------------------
# Facebook Conversion API via GTM
#
<script>
var API_VERSION = ""; // get it here: https://developers.facebook.com/docs/graph-api/guides/versioning/
var PIXEL_ID = ""; // your Facebook Pixel ID
var TOKEN = ""; // your Facebook Access Token (find it under Events Manager > Data sources)
var TEST_EVENT_CODE = ""; // your Test Event Code
var timestamp = Math.floor(Date.now() / 1000); // time now
var pageUrl = {{Page URL}}; // use the built-in GTM variable
var userAgent = navigator.userAgent; // get user's browser agenct
var clientIP = {{Client IP}}; // create a new Custom JS function. See "Get Client IP"
var payload = {
"data": [
{
"event_name": "ViewContent", // whatever event you need
"event_time": timestamp,
"event_source_url": pageUrl,
"user_data": {
"client_ip_address": clientIP,
"client_user_agent": userAgent,
// include other parameters you need
// See: https://developers.facebook.com/docs/marketing-api/conversions-api/parameters
}
}
],
"test_event_code": TEST_EVENT_CODE
};
var URL = "https://graph.facebook.com/" + API_VERSION + "/" + PIXEL_ID + "/events?access_token=" + TOKEN + "}";
window.fetch(URL, {
method: "POST",
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(payload)
}).then(function(res) {
console.log("Facebook Conversion API data sent! response:", res);
});
</script>
#-----------------------------------------------------
# Add jQuery support
#
# Notes:
# - Create this as a Tag using 'Custom HTML'
# - You can search for 'gtm-iframe' in your DOM to make sure this has loaded correctly
# - Use the Advanced Settings > Tag Sequencing and make sure this loads before your actual script does
# - Make sure you add the 'Container ID' and 'HTML ID' built in variables
<script>
(function() {
var el = document.createElement('script');
el.src = 'https://code.jquery.com/jquery-3.3.1.min.js';
el.async = true;
el.addEventListener('load', function() { window.google_tag_manager[{{Container ID}}].onHtmlSuccess({{HTML ID}})});
el.addEventListener('error', function() { window.google_tag_manager[{{Container ID}}].onHtmlFailure({{HTML ID}})});
el.setAttribute('data', 'gtm-iframe');
document.head.appendChild(el);
})();
</script>
#-----------------------------------------------------
# Adding GTM to a GoDaddy Website Builder website
#
You can add your GTM code (including script and noscript) in a 'HTML section'.
Reduce the header size to 1px and blend the section into your website.
Note: GoDaddy will append your code in an iFrame. See 'GoDaddy GTM Form Submission Tracking' for an example of accessing DOM elements on your website.
#-----------------------------------------------------
# GoDaddy GTM Form Submission Tracking
#
# Note: This isn't perfect! Depending on your perform or jQuery loading order, this may not execute.
#
<script type="text/javascript">
console.log('GA Event - Contact Submission');
jQuery(document).ready(function() {
// In GoDaddy Website Build, this doc ready is part of the iFrame.
console.log('iFrame doc ready');
// You'll need to access the iFrame's parent document to be able to access elements of your website
var parentDoc = jQuery(window.parent.document);
jQuery(parentDoc).ready(function() {
// Now you have access to elements of your main website
console.log('Parent doc ready');
// In this example, I'm finding a form's button and monitoring the
// text of the button to change. Once it does, I trigger a GA event
jQuery(window.parent.document).on('DOMSubtreeModified', 'form button', function(e) {
if (jQuery(e.target).text().toLowerCase() == 'sending') {
// Trigger GA event
console.log('in sending state');
window.parent.ga('send', 'event', 'button', 'click', 'Contact Form submitted');
}
});
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment