GTM Data Layer variable from Custom HTML not being sent to GA4 - google-analytics

I have an issue where a data layer value is not being passed to GA4.
When the user clicks download, I assign the title of the download to a Data Layer variable. This works.
I then check the Data Layer, and there it is. Great!
I create an additional GA4 event where I assign that variable, check it in GTM and GA Debug mode, and see nothing. Not even the parameter name with no value.
Both of these tags use the same click trigger.
I realize this is probably not ideal. Is there a way to push directly to GA4 from the Custom HTML Tag?
Thank you.
# This captures the name of the export and adds it to the Data Layer.
# Trigger is a click event.
<script>
$(".download-export-icon").click(function() {
var kp_export_company_name = $(this).closest('.export-file-list-top').find('.export-list-file-name').text();
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'event': 'kp_export_name_test',
'kp_export_company_name': kp_export_company_name
});
console.log( 'export name: '+kp_export_company_name );
});
</script>
Screenshot of custom HTML tag.
Additional Tag to send to GA4

Related

beforeunload event on Single Page Application (SPA) Website using Google Tag Manager (GTM)

I would like to track beforeunload event on SPA website, as I want to send data via GTM to datalayer. I want to track video watch time (HTML5 player) and send the data right before a user leaves the current page either to another one on the same website or completely different.
Is there a way to have this done via GTM custom HTML?
Assuming that you have a way to capture the video time in a variable, you can send that information to Google Analytics using an event listener for the beforeunload event. I’m doing that on one of my webpages to get an idea of how long users have the page open.
Here’s the code I’m using:
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script>
<script>
// Disable tracking if the opt-out cookie exists
if (document.cookie.indexOf("ga-disable-GA_MEASUREMENT_ID=true") > -1) {
window["ga-disable-GA_MEASUREMENT_ID"] = true;
}
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag("js", new Date());
gtag("config", "GA_MEASUREMENT_ID", { "anonymize_ip": true, "cookie_flags": "SameSite=None;Secure" });
</script>
<script>
window.addEventListener("beforeunload", function (e) {
gtag('event', 'Time_Spent', {
'event_category': 'Time_on_page',
'event_label': e.timeStamp.toString,
'value': 1,
'transport_type': 'beacon'
});
delete e.returnValue;
});
</script>
The first section is in the head and the second section is at the end of the body.
I put the event.timeStamp value in the event_label; you could put your video time, formatted however you like into that field as well.
I’m not sure I need the optional value field, but I have it.
The transport_type beacon tells Google to transmit the data asynchronously when the User Agent has an opportunity to do so, without delaying unload or the next navigation.
To see how long people have been spending with my page open, I go to:
Google Analytics -> Behavior -> Events -> Overview
I click on the event category (Time_on_page in my case), and then click on Event Label to get a listing of all of the values.

Google Tag Manager tracking drop down menu/list (Web app built in R-Shiny)

I have a R Shiny app that I have connected to Google Analytics using Google Tag Manager (R Shiny app means AJAX website). I am currently tracking the standard stuff like PageViews, and have set up a tag to track which Tab a user clicks on (Using Click Element).
In most tabs, I have a drop-down menu/list (can be seen in the picture). When clicking on this list to select/change the input, the click element does not fire. So clicking does not work here.
In the same picture, I have included the source html code. I highlighted what I think is important. The default input is "Age Group (Discrete)." The "option value=" and "selected" changes the input (changed to "Pyramid (Discrete)"). And it also changes in the div class="item" data-value=..." line.
I do not know how to capture when a user changes the input using Google Tag Manager. I am however able to successfully track this if I put this GA code in my JavaScript file.
$(document).on('change', 'select', function(e) {
ga('send', 'event', 'widget', 'select data', $(e.currentTarget).val());
});
But the above only works if I also have this included:
ga('create', 'UA-######', 'auto');
ga('send', 'pageview');
Which means it is double-counting pageviews (tracking page-views on GTM and the GA code above).
I prefer to track what I want using just GTM. Any help would be appreciated. Let me know if the image is hard to see (May need to zoom in). Thanks
one possible solutions is using GTM custom events:
1) adjust your code to trigger custom event instead of sending GA event:
$(document).on('change', 'select', function(e) {
dataLayer.push({
'event': 'widget data selected',
'selected_value': $(e.currentTarget).val()
});
});
This will trigger specific widget data selected select that can be catched with Custom Event Trigger. Then just use that trigger for your regular Analytics Event GTM tag.
Additionally, you might set up user-defined Data Layer variable to read the selected option value from dataLayer and use it in your tag.

Google Tag Manager - custom event - category is undefined

I have started using Google Tag Manager recently and I don't understand why one of my variables remains undefined while everything seems to be set up correctly.
Here is first the code that I use to create my datalayer:
<script>
window.dataLayer = [{
'pageCategory': 'test1',
'Device' : 'test2',
'Manufacturer': 'test3'
}];
</script>
I have created custom dimensions based on those variables and I can find them in Google Analytics. So far, everything is all right.
I then want to track a click on a button that leads the users to an external link. I use the following code:
window.dataLayer.push({
'ShopURL': url,
'ShopName': shop_name,
'PriceOffer': price,
'event': 'ClickPrice'
});
I have checked the content of each variable with a console.log and they all display the correct values.
In GTM, I have created datalayer variable for each one of them, I have created a custom event to push them to Google Analytics. I have taken "ShopName" for event_category, "Device" for event_action, "PriceOffer" for event_label.
When I look at the data in Google Analytics I see that event_category is undefined while event_action has the correct value. It looks like the event is fired correctly because I can only see it in GA when I click on the button but somehow some variables are not populated correctly.
You can see it in action here: https://www.mobilemultimedia.be/en/nokia/price-nokia-8.1 (click on one of the "check offer" button to trigger the event)
With GTM preview in the browser I see all the correct values.
Any idea?
Additional info
Here is a screenshot of the variable configuration in GTM:
I'm sorry, it's in French but you can see the variable with the right name.
I believe you have your trigger set incorrectly.
I think it might be an element click trigger right now, but you need it to be a "custom event" trigger and you should have "ClickPrice" as the event name you use to trigger.
Like so:

Google Tag Manager - How to avoid data loss

I am using Google Tag Manager to register events with Google Analytic. At one plance I am changing url on the changeof a dropdown. I want to track the same event on Google Analytics. I am worried what would happen if page is changed before event is registered with GA. Could you please let me know if there is a feature in GTM that can ensure that page is not changed before event is registered with GA.
Here is the code that will execute on the change of the dropdown
var targetCityChangedEventName = "TargetCityChanged";
$("#location", topHeader).bind({
"change": function(ev, obj) {
dataLayer.push({event : targetCityChangedEventName });
var url = "http://" + window.location.host + "/" + $(this).val();
window.location = url;
}
});
If you are using ga.js (asynchronous Analytics) you can set an hit callback (a macro that returns a function) in the tag template under "advanced configuration and do the redirect there (possibly you'd need a separate analytics tag just the change event).
If you use Universal Analytics there was a discussion at the Tag Manager Google Group a while ago where Googles Brian Kuhn suggested the following way ( I have not tested this):
In the meantime, have you tried this?
dataLayer.push({callback:
function() {
alert(123);
});
Then, create a dataLayer macro that reads the "callback" key. Then,
use that macro as the value of a "fields to set" pair on your UA tag,
under the field name "hitCallback".
Instead of the alert you'd do the redirect.
In case that's not clear, a hit callback is a function that can be passed to the tracking calls and is executed after the tracking call has executed.
I was able to resolve the same issue by simply inserting a delay. The dataLayer.push doesn't need to return anything, so a 100 millisecond delay is sufficient in 99% of the cases for the dataLayer.push to be executed.
dataLayer.push({ ... });
setTimeout( function(){ window.location = ...; }, 100 );
Note that the GTM preview/debug mode gives false positives - you must make sure that your tags are actually being fired, in my case my event was for a virtual pageview and I could see the results in RealTime Analytics. Without the delay, I could see that the tag was not being fired.

Create dataLayer custom event for external clicks

I am looking to create a dataLayer push event for any time a click is made on any external link - I plan to use it as a trigger to fire a GTM tag for external link tracking. I envision it will be something like this :
<script>
Some code to detect clicks on any external links
dataLayer.push({'event': 'eventNameXYZ'});
</script
An example function:
function pushToDataLayer() {
var links = document.getElementsByTagName('a');
for(var i=0,cnt=links.length;i<cnt;i++) {
var current = links[i];
current.onclick = function() {
dataLayer.push({
'href': current.href,
'event': 'outbound' // event to trigger a rule in the tag manager
});
}
}
}
(This will be much easier if you use jQuery or something like it). This will attach an click event to all links. The click will push an event and a variable with the clicked href to the dataLayer.
In the Tag Manager you need to create a new rule that triggers a tag on the custom event "outbound" and a Macro with the type dataLayer that catches the "href" dataLayer Variable. You can use this variable in your tags - for example with a GA virtual ´pageview - and have the tags fire with the rule "fire on event "outbound".
The code might not work on all browsers and is a demonstration of a principle rather than production code (plus it will catch all links, you'd need to test for absolute urls or domains name or css class names that suggest an outbound link). I would recommend using jQuery for finding the links and attaching events.

Resources