virling Pricing Self-host Demo Changelog Agencies GitHub Start free trial
blog / 2026-11-24

Capture UTM parameters in hidden fields: JavaScript snippet

By Devendra Variya, co-founder of Virling. Published 2026-11-24.

To capture UTM parameters in hidden fields, add one hidden input per tag to your form, named utm_source, utm_medium and so on. Then run a short script that reads the tags from the page address and writes them into those inputs. Save the tags in a first-party cookie as well, because most visitors do not fill in the form on the page they landed on. The tags then arrive with the lead, like any other field. What they cannot tell you is whether that lead paid, and the second half of this page covers that.

Step 1: add the hidden inputs

Put these inside the <form>. Form builders usually have a hidden field type; give each field the same name.

<input type="hidden" name="utm_source">
<input type="hidden" name="utm_medium">
<input type="hidden" name="utm_campaign">
<input type="hidden" name="utm_content">
<input type="hidden" name="utm_term">
<input type="hidden" name="virling_vid">

The last one is optional. It carries the Virling visitor ID, which you need later to join the lead to a payment. Leave it out if you do not use Virling.

Step 2: add the snippet

Put this on every page, not only the one with the form, so the landing page can save the tags. It is plain JavaScript with no library. Save it as a file and load it with defer, or paste it in a <script> tag before </body>.

(function () {
  var KEYS = ["utm_source", "utm_medium", "utm_campaign", "utm_content", "utm_term"];
  var MAX = 100;
  var DOMAIN = ""; // "example.com" shares the cookie with subdomains

  function parse(query) {
    var from = new URLSearchParams(query || ""), tags = {};
    KEYS.forEach(function (k) {
      var v = Array.from((from.get(k) || "").trim()).slice(0, MAX).join("");
      if (v) tags[k] = v;
    });
    return tags;
  }

  // The URL wins as a whole set, so two campaigns never mix
  function read(search, saved) {
    var tags = parse(search);
    return Object.keys(tags).length ? tags : parse(saved);
  }

  function save(tags) {
    var value = new URLSearchParams(tags);
    KEYS.slice().reverse().forEach(function (k) {
      if (value.toString().length > 3800) value.delete(k);
    });
    document.cookie = "lead_utm=" + value + "; path=/; max-age=7776000; SameSite=Lax" +
      (DOMAIN ? "; domain=" + DOMAIN : "") +
      (location.protocol === "https:" ? "; Secure" : "");
  }

  var saved = (document.cookie.match(/(?:^|; )lead_utm=([^;]*)/) || [])[1];
  var tags = read(location.search, saved);
  if (Object.keys(parse(location.search)).length) save(tags);

  function fill(root) {
    KEYS.forEach(function (k) {
      root.querySelectorAll('input[type="hidden"][name="' + k + '"]').forEach(function (el) {
        el.value = tags[k] || "";
      });
    });
    root.querySelectorAll('input[type="hidden"][name="virling_vid"]').forEach(function (el) {
      el.value = window.virling?.vid?.() || "";
    });
  }

  window.leadUtm = { read: read, fill: fill, tags: tags };
  document.addEventListener("submit", function (e) { fill(e.target); }, true);
  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", function () { fill(document); });
  } else {
    fill(document);
  }
})();
  • Missing tags. The field is left empty. Nothing is guessed, and an untagged page does not erase the saved tags.
  • Very long tags. Each value is cut to 100 characters. If the set is still too big for a cookie, the snippet drops utm_term first, then utm_content, and so on up, from the cookie only.
  • Two campaigns. A new tagged visit replaces the whole saved set, so the source of one link never sits next to the campaign of another. This keeps the last tagged visit. To keep the first instead, change the read line to read(saved, location.search) and call save only when saved is empty.
  • Forms added later. The fields are filled again when a form is submitted, so a form in a popup works too.
  • Unsafe values. The script only sets an input’s value and never writes HTML. Your server should still treat the fields as text a stranger typed: check the length and escape them, because anyone can edit a hidden field.

The cookie lasts 90 days, but Safari caps a cookie set by a script at seven days (source: WebKit). For other ways to keep the tags, see how to persist UTM parameters across pages. Saving tags in the browser may need consent where you sell. If you wait for consent, load the snippet from your consent tool. If the tags are gone before the page loads, see UTM parameters lost after redirect.

Step 3: test it

Open a page with the snippet, paste this in the browser console and look for nine lines that say pass.

(function () {
  var read = window.leadUtm.read, count = function (o) { return Object.keys(o).length; };
  var tests = {
    "reads the URL": read("?utm_source=news&utm_medium=email", "").utm_medium === "email",
    "falls back to the cookie": read("", "utm_source=news").utm_source === "news",
    "URL wins over the cookie": read("?utm_source=a", "utm_source=b").utm_source === "a",
    "never mixes two sets": !read("?utm_source=a", "utm_campaign=old").utm_campaign,
    "missing tags": count(read("", undefined)) === 0,
    "empty tag": count(read("?utm_source=&utm_medium=%20", "")) === 0,
    "very long tag": read("?utm_source=" + "x".repeat(5000), "").utm_source.length === 100,
    "broken encoding": read("?utm_source=100%", "").utm_source === "100%",
    "ignores other parameters": count(read("?email=a%40example.com&q=1", "")) === 0
  };
  Object.keys(tests).forEach(function (name) {
    console.log(tests[name] ? "pass" : "FAIL", name);
  });
})();

Then test the whole path by hand:

  1. Open your site in a private window with ?utm_source=test&utm_medium=email on the end
  2. Click through to the page with the form, so the tags leave the address bar
  3. Run document.querySelector('[name="utm_source"]').value in the console. It should say test
  4. Send the form and find the tags on the lead
  5. Do it again in a new private window without tags. The fields should be empty and the form should still send

Build the link with the UTM builder so the names match your other campaigns.

Embedded forms in an iframe

If your form provider gives you an iframe, the form lives on another domain. The browser does not let your page reach into it, the form cannot read your cookie, and its address is not your page address. A script on your page cannot fill its hidden fields. Two things work:

  • Use the script embed instead, if the provider has one that renders the form in your page. Then the inputs are part of your page and the snippet fills them.
  • Put the tags in the iframe address. Many form tools can fill a hidden field from a query parameter; check yours for the exact setting. For Typeform, see Typeform hidden fields for UTM tracking; for Tally, see Tally hidden fields for UTM tracking. If the page inside is yours, add the snippet to it and it reads its own address.

For the second one, use data-src so the frame loads once, with the tags already on it. Put this after the snippet:

<iframe data-src="https://forms.example.net/demo" title="Book a demo"></iframe>
<script>
document.querySelectorAll("iframe[data-src]").forEach(function (frame) {
  var url = new URL(frame.dataset.src);
  var tags = window.leadUtm ? window.leadUtm.tags : {};
  Object.keys(tags).forEach(function (k) { url.searchParams.set(k, tags[k]); });
  frame.src = url.href;
});
</script>

If you load the snippet with defer, put this code in the same file after it. For the visitor ID, add url.searchParams.set("virling_vid", window.virling?.vid?.() || "") once the Virling script has loaded.

Multi-step forms

  • Each step is its own page. The tags are gone from the address by step two. Put the hidden inputs on the last step, the one that sends the lead, and the cookie fills them.
  • Steps change within one page. If the last step is still a real form submit, the fields are filled as it is sent, even if they were added a moment before.
  • Your code sends the data itself. With no submit event, call leadUtm.fill(form) just before you read the form, or add leadUtm.tags to the data you send.
  • You save partial leads. Store the tags with the first step on your server and do not let an empty value from a later step replace them.

What a lead form cannot tell you

A hidden field is written once, when the form is sent. Everything after that is out of its reach:

  • Who paid. The payment happens later, often in another tool, with nothing on it that points back to the form.
  • How much, and for how long. Plan size, refunds and renewals are not known yet.
  • Untagged visits. Search, AI answers and plain links carry no tags, so the fields are empty or show an older campaign.
  • The other visits. One set of tags stands in for every visit the lead made before the form.

That matters because the channel with the most leads is not always the one that pays. These numbers are made up for the example:

utm_sourceLeadsPaidFirst-year revenuePer lead
newsletter402$600$15
partner104$4,800$480

The form alone shows the source and the number of leads. The lead value calculator does the rest of the sum once you know how many leads paid. For leads whose fields are empty, ask them: the how did you hear about us template has ready answer options. It tells you what people remember, so read it next to the tags and not instead of them.

Join the lead to a payment

With Virling you do not need the tags on the payment. The script records each visit with its tags and referrer, under a visitor ID in the virling_vid cookie. The payment only has to find that visitor, in one of two ways. Leave cookieless mode off: without the cookie there is no visitor ID to carry.

By visitor ID, when the lead pays through your checkout

Save the virling_vid field with the lead, then pass it when your server creates the checkout. For Stripe, set client_reference_id or metadata.virling_vid:

await stripe.checkout.sessions.create({
  client_reference_id: lead.virling_vid || undefined,
  // ...
});

If the lead pays in the same browser, your server can read the virling_vid cookie and you need no field. The field for each provider is in link checkout to visits.

By email, when the lead pays an invoice

An invoice you send from Stripe does not pass through a checkout on your site, so it has no visitor ID. Send the lead’s email once, as an identify event, when the form succeeds:

// After the demo or signup form succeeds
fetch("https://app.virling.com/api/event", {
  method: "POST",
  keepalive: true,
  body: JSON.stringify({ n: "identify", u: location.href, s: "yourproduct.com", v: window.virling?.vid?.(), m: email }),
});

keepalive lets the request finish if the form then opens a thank-you page. Virling keeps only a SHA-256 hash of the trimmed, lowercased email with a salt of your site. A Stripe, Shopify or WooCommerce payment with no visitor ID whose payer email matches is credited to that visitor and shows Matched by email on the Payments page. Matching is exact, never crosses sites and applies to payments synced after the identify, so send it at the demo request and not after the deal closes. If the demo is booked through Cal.com rather than a form, the Cal.com booking guide passes the tags and visitor ID into the booking.

If a form tool sends you the lead by webhook, your server can send the same event: use the saved virling_vid as v, a page of your site as u, and set a User-Agent header, since events with an empty or automated one are dropped. Do not send it without a visitor ID, or the email is tied to your server and not to the lead.

Add virling("goal", "demo request") next to it and the request shows up in the payment’s journey. The whole setup is in the sales-led B2B guide. Stripe invoice attribution goes through the invoice side, and B2B SaaS attribution for small teams covers what else to track.

What still stays unattributed

  • A different payer. If an accounts team pays the invoice, the emails do not match.
  • No identify before the payment. The form did not send the email, or the payment was synced first.
  • No visit in the window. The lead is known, but their visits started before the lookback window, 90 days by default.
  • A visit that was never tracked. The script was missing or blocked, the visitor had Global Privacy Control with data-respect-gpc, or the visit was filtered as a bot.

Those payments still count toward revenue, as Unattributed. Every cause is in unattributed revenue.

Start free trial See the demo

Frequently asked questions

How do I capture UTM parameters in hidden fields?

Add one hidden input per tag to the form, then run a script that reads the tags from the page address and writes them into those inputs. Save the tags in a first-party cookie too, so the form still gets them when the visitor fills it in on a later page.

Why are my hidden UTM fields empty?

Usually the visitor landed on one page and filled in the form on another, so the address no longer had the tags. Other causes are a redirect that dropped the tags, input names that do not match, a form inside an iframe, or a visit with no tags at all.

Can I fill hidden fields inside an iframe form?

Not from the outside when the iframe is on another domain, because the browser blocks access to it. Add the tags to the iframe address instead, and have the form inside read its own address or use the form provider's prefill setting.

What happens if a UTM tag is missing or very long?

With the snippet on this page, a missing tag leaves its field empty and a long one is cut to 100 characters. Check the length again on your server, because anyone can edit a hidden field.

Can a hidden field tell me which leads paid?

No. It is written when the form is sent, before any payment. To know who paid, pass the visitor ID into checkout or send the lead's email in an identify event, so a payment can be joined to the lead's visits.

See which leads turned into revenue

Virling is open source under AGPL. Self-host it free, or use the hosted version with a 14-day free trial. It connects to Stripe, Paddle, Shopify, WooCommerce, Polar, LemonSqueezy, Dodo, Creem and RevenueCat.

Start free trial See the demo