This guide walks through how to retrieve UTM parameters from the URL and dynamically append them as hidden input fields within a Webflow form. By targeting the correct form element, the hidden inputs can be seamlessly added—only when UTM data is present—ensuring the form still functions normally otherwise. This technique strengthens marketing attribution and analytics, making it easier to assess the effectiveness of campaigns. Before publishing, be sure to review the custom code for accuracy and proper implementation.
Example code that can be used to look for UTM parameters and add them to the target form.
// Wait for the DOM to be fully loaded before executing the script
window.addEventListener("DOMContentLoaded", function () {
// Get the form element by its ID
const form = document.getElementById("form");
// If the form doesn't exist on the page, stop execution
if (!form) return;
// Define a whitelist of allowed UTM parameters for security
const allowedParams = new Set([
"utm_source",
"utm_medium",
"utm_campaign",
"utm_term",
"utm_content"
]);
// Parse the URL's query string into key-value pairs
const params = new URLSearchParams(window.location.search);
// If there are no query parameters, exit early
if ([...params].length === 0) return;
// Loop through each query parameter
params.forEach(function (value, key) {
// Only process parameters that are explicitly allowed
if (!allowedParams.has(key)) return;
// Sanitize the value by removing potentially dangerous characters
// This keeps only alphanumeric characters, underscores, dashes, and spaces
const sanitizedValue = value.replace(/[^\w\s-]/g, "").trim();
// Skip appending if the sanitized value is empty
if (!sanitizedValue) return;
// Create a hidden input field with the sanitized key and value
const input = document.createElement("input");
input.type = "hidden";
input.name = key;
input.value = sanitizedValue;
// Append the hidden input to the form
form.appendChild(input);
});
});
Inspect and clone this project to investigate/test as needed: https://webflow.com/made-in-webflow/website/hidden-utm-params-in-form.
document.getElementById("form")
. In Webflow, form elements often have auto-generated IDs unless explicitly set.document.querySelector("form")
if there's only one form on the page.utm_source
vs UTM_Source
). Normalize if needed.?email=john@example.com
), it will be captured and submitted. You may want to filter or block unexpected fields.sessionStorage
or cookies for retrieval later (if applicable).