Skip to content

Instantly share code, notes, and snippets.

@bjornpagen
Created January 31, 2023 03:20
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjornpagen/bcea5037d61dc29b218cc00a20f5f327 to your computer and use it in GitHub Desktop.
Save bjornpagen/bcea5037d61dc29b218cc00a20f5f327 to your computer and use it in GitHub Desktop.
A JavaScript code snippet for logging UTM parameters as a GA4 event, only including parameters that are set in the URL and omitting any parameters that are not set.
// Get the UTM parameters from the URL
var search = window.location.search;
var params = new URLSearchParams(search);
// Keep track of if an event has already been logged
var eventLogged = false;
// Loop through each UTM parameter
for (var [key, value] of params.entries()) {
// Check if the parameter is "utm_source", "utm_medium", "utm_campaign", "utm_term", or "utm_content"
if (["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"].indexOf(key) !== -1) {
// Check if an event has not yet been logged
if (!eventLogged) {
// Log the UTM parameters as an event in GA4
gtag("event", "UTM Parameters", {
event_category: "UTM",
event_label: [
params.get("utm_source") && "utm_source: " + params.get("utm_source"),
params.get("utm_medium") && "utm_medium: " + params.get("utm_medium"),
params.get("utm_campaign") && "utm_campaign: " + params.get("utm_campaign"),
params.get("utm_term") && "utm_term: " + params.get("utm_term"),
params.get("utm_content") && "utm_content: " + params.get("utm_content")
]
.filter(Boolean)
.join(", ")
});
// Set eventLogged to true so the event is not logged again
eventLogged = true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment