diff --git a/blocks/form/utm.js b/blocks/form/utm.js index fbc29148..e3276c97 100644 --- a/blocks/form/utm.js +++ b/blocks/form/utm.js @@ -1,5 +1,4 @@ // eslint-disable-next-line import/no-unresolved -import { fetchPlaceholders } from '../../../../../../../scripts/aem.js'; const createUtmInput = (name, value, form) => { const input = document.createElement('input'); @@ -9,13 +8,33 @@ const createUtmInput = (name, value, form) => { form.appendChild(input); }; +/* eslint-disable no-else-return, no-undef */ +async function getECID() { + if (typeof alloy === 'function') { + try { + const result = await alloy('getIdentity'); + if (result && result.identity && result.identity.ECID) { + return result.identity.ECID; + } else { + console.warn('Alloy returned no ECID. Check your configuration.'); + } + } catch (error) { + console.error('Error getting ECID:', error); + } + } else { + console.error('Alloy.js is not available on this page.'); + } + return null; +} +/* eslint-enable no-else-return, no-undef */ + export default async function decorateUTM(form) { - const placeholders = await fetchPlaceholders('/forms/utm-sources'); - const utmSources = placeholders ? Object.values(placeholders).join(',') : null; const utmParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content']; const queryString = window.location.search; const urlParams = new URLSearchParams(queryString); - utmParams.forEach((item) => { + let hasMediium = false; + for (let i = 0; i < utmParams.length; i += 1) { + const item = utmParams[i]; let utmValue = urlParams.get(item); const now = new Date(); const minutes = 30; @@ -25,22 +44,21 @@ export default async function decorateUTM(form) { if (utmValue != null && utmValue !== '') { createUtmInput(item, utmValue, form); document.cookie = `${item}=${utmValue}; path=/; expires=${now.toUTCString()}`; + hasMediium = item === 'utm_medium' ? true : hasMediium; } else if (document.cookie.split('; ').find((row) => row.startsWith(`${item}=`))) { // eslint-disable-next-line prefer-destructuring utmValue = document.cookie.split('; ') .find((row) => row.startsWith(`${item}=`)) .split('=')[1]; createUtmInput(item, utmValue, form); // Create input dynamically using cookie value - } else if (item === 'utm_medium' || item === 'utm_source') { - // Check if utm_medium or utm_source can be determined from the referrer - if (utmSources && document.referrer) { - const url = document.referrer.match(/:\/\/(.[^/]+)/)[1]; - if (utmSources.includes(url)) { - utmValue = item === 'utm_medium' ? 'organic' : document.referrer; - document.cookie = `${item}=${utmValue}; path=/; expires=${now.toUTCString()}`; - createUtmInput(item, utmValue, form); // Create input dynamically from referrer - } - } + hasMediium = item === 'utm_medium' ? true : hasMediium; + } + } + + if (!hasMediium) { + const ecid = await getECID(); + if (ecid) { + createUtmInput('utm_content', ecid, form); } - }); + } }