
In this post we will explore how to capture UTMs, store them in a cookie and save them for 30 days. Once that is complete we will look for any iframe windows loaded on the page and add the utms to the Iframe Source url. Doing it this way will make the UTMs present in the iframe window which will allow the iframe itself to capture them simply. Trim this code as needed to accomplish your goals.
/* ================================================================
1. UTM CAPTURE → COOKIE (30 days)
================================================================ */
(function () {
'use strict';
function setCookie(name, value, days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
const expires = '; expires=' + date.toUTCString();
document.cookie = name + '=' + encodeURIComponent(JSON.stringify(value)) + expires + '; path=/; SameSite=Lax';
}
function getCookie(name) {
const nameEQ = name + '=';
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1);
if (c.indexOf(nameEQ) === 0) {
return JSON.parse(decodeURIComponent(c.substring(nameEQ.length, c.length)));
}
}
return null;
}
function captureUTMs() {
const params = {};
const query = window.location.search.substring(1);
const vars = query.split('&');
for (let i = 0; i < vars.length; i++) {
const pair = vars[i].split('=');
const key = decodeURIComponent(pair[0]).toLowerCase();
if (key.startsWith('utm_')) {
params[key] = decodeURIComponent(pair[1] || '');
}
}
return params;
}
const utmsFromUrl = captureUTMs();
const existingUtms = getCookie('utmParams') || {};
const finalUtms = {};
const keys = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'];
for (const k of keys) {
finalUtms[k] = utmsFromUrl[k] || existingUtms[k] || '';
}
if (Object.values(finalUtms).some(v => v)) {
setCookie('utmParams', finalUtms, 30);
}
window.utmParams = finalUtms;
})();
/* ================================================================
2. DYNAMIC IFRAME – FROM COOKIE
================================================================ */
(function () {
function getCookie(name) {
const nameEQ = name + '=';
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1);
if (c.indexOf(nameEQ) === 0) {
return JSON.parse(decodeURIComponent(c.substring(nameEQ.length, c.length)));
}
}
return null;
}
const storedUtms = getCookie('utmParams') || {};
const iframeSrc = new URL('form.html', window.location.origin);
Object.keys(storedUtms).forEach(key => {
if (storedUtms[key]) {
iframeSrc.searchParams.set(key, storedUtms[key]);
}
});
console.log('%c[PARENT] Iframe src (from cookie):', 'color:#9b59b6; font-weight:bold;', iframeSrc.toString());
const iframe = document.createElement('iframe');
iframe.src = iframeSrc.toString();
iframe.title = 'Contact Form';
iframe.style.width = '100%';
iframe.style.height = '500px';
iframe.style.border = '1px solid #ccc';
iframe.style.borderRadius = '8px';
iframe.sandbox = 'allow-forms allow-scripts allow-same-origin';
document.getElementById('iframeContainer').appendChild(iframe);
})();
/* ================================================================
3. MESSAGE LISTENER & TOAST - This is the message from the iframe so you can see the submission
================================================================ */
window.addEventListener('message', function (event) {
// Optional: restrict origin
// if (event.origin !== window.location.origin) return;
const { type, payload } = event.data || {};
console.log('%c[PARENT] Received message', 'color:#27ae60; font-weight:bold;', {
origin: event.origin,
type,
payload
});
if (type === 'FORM_SUBMITTED') {
handleFormSubmission(payload);
}
});
function handleFormSubmission(payload) {
const notification = document.createElement('div');
notification.style.cssText = `
position:fixed;top:20px;right:20px;background:#2ecc71;color:#fff;
padding:15px 20px;border-radius:8px;box-shadow:0 4px 12px rgba(0,0,0,.2);
z-index:10000;font-family:Arial;max-width:300px;
animation:slideIn .4s ease;
`;
notification.innerHTML = `
<strong>New Message!</strong><br>
<small>From: ${escapeHtml(payload.name || '—')} <${escapeHtml(payload.email || '—')}></small>
`;
document.body.appendChild(notification);
setTimeout(() => {
notification.style.animation = 'slideOut .4s ease';
setTimeout(() => notification.remove(), 400);
}, 5000);
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
const style = document.createElement('style');
style.textContent = `
@keyframes slideIn { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
@keyframes slideOut { to { transform: translateX(100%); opacity: 0; } }
`;
document.head.appendChild(style);Iframe Source Code:
Use this code inside the Iframe to capture the UTMs from the source URL and apply them to the form.
// Log iframe URL + UTMs on load
console.log('%c[IFRAME] Loaded from URL:', 'color:#9b59b6; font-weight:bold;', window.location.href);
const utms = Array.from(new URLSearchParams(window.location.search))
.filter(([k]) => k.startsWith('utm_'))
.reduce((obj, [k, v]) => ({ ...obj, [k]: v }), {});
if (Object.keys(utms).length) {
console.log('%c[IFRAME] Detected UTMs:', 'color:#e67e22; font-weight:bold;', utms);
} else {
console.log('%c[IFRAME] No UTM parameters found.', 'color:#95a5a6;');
}
const form = document.getElementById('contactForm');
const successMessage = document.getElementById('successMessage');
/* ================================================================
1. UTM CAPTURE FROM IFRAME URL + INJECT HIDDEN FIELDS
================================================================ */
(function () {
'use strict';
const urlParams = window.location.urlParams || {};
console.log(urlParams)
// Read UTMs from this iframe's URL
function getUtmsFromUrl() {
var query = window.location.search.substring(1);
var pairs = query.split('&');
var utms = {};
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
var key = decodeURIComponent(pair[0]).toLowerCase();
if (key.indexOf('utm_') === 0) {
utms[key] = decodeURIComponent(pair[1] || '');
}
}
return utms;
}
var utms = getUtmsFromUrl();
if (Object.keys(utms).length === 0) return;
var form = document.getElementById('contactForm');
if (!form) return;
var fields = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'];
fields.forEach(function (name) {
if (utms[name]) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = name;
input.value = utms[name];
form.appendChild(input);
}
});
console.log('UTM hidden fields injected:', utms);
})();
// ---------- 1. Extract iframe URL parameters ----------
const urlParams = new URLSearchParams(window.location.search);
const urlParamsObj = Object.fromEntries(urlParams.entries());
form.addEventListener('submit', function (e) {
e.preventDefault();
// ---------- 2. Collect ALL form fields ----------
const formData = new FormData(form);
const payload = {
timestamp: new Date().toISOString(),
urlParams: urlParamsObj // <-- NEW: include iframe query string
};
// Loop through every form entry
for (const [key, value] of formData.entries()) {
if (payload[key] !== undefined) {
// Support multiple values (checkboxes, etc.)
if (Array.isArray(payload[key])) {
payload[key].push(value);
} else {
payload[key] = [payload[key], value];
}
} else {
payload[key] = value;
}
}
// Trim strings
Object.keys(payload).forEach(k => {
if (typeof payload[k] === 'string') payload[k] = payload[k].trim();
});
// ---------- 3. Log & send ----------
console.log('%c[IFRAME] Sending postMessage', 'color:#3498db; font-weight:bold;', {
type: 'FORM_SUBMITTED',
payload
});
window.parent.postMessage({
type: 'FORM_SUBMITTED',
payload
}, '*'); // <-- replace '*' with your domain in prod
// ---------- 4. Local UI ----------
form.reset();
});
Reach out to us today. We are always working to improve our services so you can stay on top of your digital marketing goals. Simply fill out our online form to get jump-start your digital marketing today!