Skip to content

Marketing skills for Claude Code and AI agents. CRO, copywriting, SEO, analytics, and growth engineering.

fix(conversion-tracking): ship the listeners proven by live checks

Aaron Beashelc8760ffcad1c
diff --git a/VERSIONS.md b/VERSIONS.md
index e81d10f..5bf8f75 100644
--- a/VERSIONS.md
+++ b/VERSIONS.md
@@ -63,7 +63,7 @@ Current versions of all skills. Agents can compare against local versions to che
- Added the **`conversion-tracking`** skill (1.0.0). Setting up, auditing, verifying and fixing the path from a conversion on a website to Google Ads, Meta, GA4, LinkedIn, TikTok and Microsoft Ads, for lead generation and ecommerce. Gives an orphaned job a home. Analytics listed conversion tracking as a trigger without covering it, attribution routed pixels and CAPI to ads, and ads held one reference file. Built on one distinction, that lead gen has to infer success from a browser signal while ecommerce reads it from an order record. Nine references (how each form, booking and chat tool signals success, the complete browser-side path, the server-side options with prices, ecommerce platforms including Shopify's 26 Aug 2026 Additional Scripts removal, Google Ads, Meta, other platforms, the audit playbook, and why the numbers never match), 22 detection snippets, importable GTM recipes merged by `scripts/build_recipe.py`, and 16 evals. Audit scoring follows the ads skill's audit guardrails, summarised inline. New skill = repo y release; total skills: 51. Contributed by Aaron Beashel (Converly ◆, a Verified Partner) and reviewed against the repo's partner-integrity bar before merge:
- **Neutrality:** free and native paths first (browser Enhanced Conversions, Meta advanced matching, Google tag gateway, Meta CAPI Gateway, tool webhooks); a "when server-side matters less" section; the partner row matches the others in length and lists its tradeoffs; a free-tier row in the side-by-side; paid options surface at the delivery decision, not in every answer; the contributor's other tool (Attributer) is disclosed with alternatives; five neutrality evals (ids 17–21) and one delivery-decision eval (id 22).
- **Facts:** browser tags can send hashed email and phone; Meta dropped the AEM 8-event cap in May 2023; Microsoft has a Conversions API (self-serve token, still rolling out); LinkedIn dedup needs a shared `eventId`; Meta CAPI for CRM gates; Google tROAS vs tCPA minimums; conversion-adjustment windows; Shopify's 1 Oct 2026 script-tag change; the undercount stated as a 10–30% range rather than a universal 30%.
- - **Assets:** Jotform source-code embeds fire once the submission is built, with the iframe message kept as a fallback; Framer listens before its own handler cancels the submit; 10 drifted GTM recipes regenerated from their snippets, with `scripts/check_recipes.py` to keep them in sync; `build_recipe.py` validates every ID and substitutes safely (no JSON or JS injection) on Python 3.8+; every send tag requires consent (the Google Ads conversion tag `ad_storage` only); snippet success-signal types documented.
+ - **Assets:** 15 detection snippets replaced with listeners that passed live checks on real forms, Jotform's now firing on the completion message its iframe and script embeds send, and Framer's confirming through Framer's own form request; every GTM recipe uses Tag Manager's import format, so Import Container accepts it; 10 drifted GTM recipes regenerated from their snippets, with `scripts/check_recipes.py` to keep them in sync; `build_recipe.py` validates every ID and substitutes safely (no JSON or JS injection) on Python 3.8+; every send tag requires consent (the Google Ads conversion tag `ad_storage` only); snippet success-signal types documented.
- **Repo fit:** operative rules in the description, a revops boundary, no cross-skill relative links, two audit checks restored from the retired ads reference.
- **Converly integration guide** filled in (capabilities, setup, operations); platform lift stats carry a holdout caveat.
- **analytics** (2.0.1 → 2.0.2): description drops the "conversion tracking" and "track conversions" triggers and hands getting conversions into ad platforms to conversion-tracking.
diff --git a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-calendly.json b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-calendly.json
index d5ff1da..c3083e2 100644
--- a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-calendly.json
+++ b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-calendly.json
@@ -29,7 +29,7 @@
{
"type": "TEMPLATE",
"key": "html",
- "value": "<script>\n(function () {\n if (window.__ctDetectCalendly) return;\n window.__ctDetectCalendly = true;\n window.dataLayer = window.dataLayer || [];\n\n var ORIGIN_PATTERN = /(^|\\.)calendly\\.com$/;\n\n function fireConversion(eventUri, inviteeUri) {\n window.dataLayer.push({\n event: 'calendly_event_scheduled',\n event_uri: eventUri || '',\n invitee_uri: inviteeUri || ''\n });\n }\n\n function looksLikeCalendlyScheduled(data) {\n if (!data || typeof data !== 'object') return false;\n return data.event === 'calendly.event_scheduled';\n }\n\n function onMessage(event) {\n if (!event || !event.source) return;\n if (event.source === window) return;\n if (!event.origin || typeof event.origin !== 'string') return;\n\n var hostMatch = /^https:\\/\\/([^/]+)$/.exec(event.origin);\n if (!hostMatch) return;\n if (!ORIGIN_PATTERN.test(hostMatch[1])) return;\n\n var data = event.data;\n if (typeof data === 'string') {\n try { data = JSON.parse(data); } catch (e) { return; }\n }\n if (!looksLikeCalendlyScheduled(data)) return;\n\n var payload = data.payload || {};\n var inviteeUri = payload.invitee && payload.invitee.uri;\n var eventUri = payload.event && payload.event.uri;\n if (!inviteeUri || !eventUri) return;\n\n fireConversion(eventUri, inviteeUri);\n }\n\n window.addEventListener('message', onMessage, false);\n})();\n</script>"
+ "value": "<script>\n(function () {\n 'use strict';\n if (window.__ctDetectCalendly) return;\n window.__ctDetectCalendly = true;\n window.dataLayer = window.dataLayer || [];\n\n // The CSS selector matches only Calendly's documented exact embed host.\n // Do not read iframe.src or its `src` attribute: prefill parameters can\n // contain invitee PII. The selector engine performs the prefix match without\n // exposing the URL value to this listener.\n var CALENDLY_FRAME_SELECTOR = 'iframe[src^=\\\"https://calendly.com/\\\"]';\n var CALENDLY_ORIGIN = 'https://calendly.com';\n var API_HOSTS = { 'api.calendly.com': true, 'calendly.com': true };\n var trackedFrames = [];\n var seenPairs = [];\n\n function trackFrame(frame) {\n if (!frame || !frame.contentWindow) return;\n for (var i = 0; i < trackedFrames.length; i++) {\n if (trackedFrames[i].frame === frame) {\n trackedFrames[i].source = frame.contentWindow;\n trackedFrames[i].origin = CALENDLY_ORIGIN;\n return;\n }\n }\n trackedFrames.push({ frame: frame, source: frame.contentWindow, origin: CALENDLY_ORIGIN });\n }\n\n function scan(root) {\n if (!root || typeof root.querySelectorAll !== 'function') return;\n var frames;\n try { frames = root.querySelectorAll(CALENDLY_FRAME_SELECTOR); } catch (e) { return; }\n for (var i = 0; i < frames.length; i++) trackFrame(frames[i]);\n }\n\n function sourceIsTracked(event) {\n for (var i = 0; i < trackedFrames.length; i++) {\n var item = trackedFrames[i];\n try {\n if (item.frame.isConnected === true && item.frame.contentWindow === event.source && item.source === event.source && item.origin === event.origin) return true;\n } catch (e) { /* replaced or inaccessible frames fail closed */ }\n }\n return false;\n }\n\n function resourceIdentity(value, kind) {\n if (typeof value !== 'string' || /[?#]/.test(value)) return null;\n try {\n var url = new URL(value);\n if (url.protocol !== 'https:' || url.port || !API_HOSTS[url.hostname]) return null;\n var eventMatch = /(?:^|\\/)scheduled_events\\/([A-Za-z0-9_-]{1,128})\\/?$/.exec(url.pathname);\n var inviteeMatch = /(?:^|\\/)scheduled_events\\/([A-Za-z0-9_-]{1,128})\\/invitees\\/([A-Za-z0-9_-]{1,128})\\/?$/.exec(url.pathname);\n if (kind === 'event' && eventMatch) return { eventId: eventMatch[1].toLowerCase() };\n if (kind === 'invitee' && inviteeMatch) return { eventId: inviteeMatch[1].toLowerCase(), inviteeId: inviteeMatch[2].toLowerCase() };\n } catch (e) { return null; }\n return null;\n }\n\n function pairSeen(eventId, inviteeId) {\n var key = eventId + ':' + inviteeId;\n for (var i = 0; i < seenPairs.length; i++) if (seenPairs[i] === key) return true;\n seenPairs.push(key);\n return false;\n }\n\n function onMessage(message) {\n if (!message || !message.source || message.source === window || !sourceIsTracked(message)) return;\n var data = message.data;\n if (typeof data === 'string') {\n try { data = JSON.parse(data); } catch (e) { return; }\n }\n if (!data || typeof data !== 'object' || data.event !== 'calendly.event_scheduled') return;\n var payload = data.payload || {};\n var eventUri = payload.event && payload.event.uri;\n var inviteeUri = payload.invitee && payload.invitee.uri;\n var eventIdentity = resourceIdentity(eventUri, 'event');\n var inviteeIdentity = resourceIdentity(inviteeUri, 'invitee');\n if (!eventIdentity || !inviteeIdentity || eventIdentity.eventId !== inviteeIdentity.eventId) return;\n if (pairSeen(eventIdentity.eventId, inviteeIdentity.inviteeId)) return;\n window.dataLayer.push({ event: 'calendly_event_scheduled', event_uri: eventUri, invitee_uri: inviteeUri });\n }\n\n function start() {\n if (typeof document === 'undefined') return;\n scan(document);\n if (typeof MutationObserver === 'undefined' || !document.documentElement) return;\n try {\n var observer = new MutationObserver(function (mutations) {\n for (var i = 0; i < mutations.length; i++) {\n var added = mutations[i].addedNodes || [];\n for (var j = 0; j < added.length; j++) {\n var node = added[j];\n if (node && node.tagName === 'IFRAME') scan(document);\n else scan(node);\n }\n if (mutations[i].type === 'attributes' && mutations[i].attributeName === 'src') scan(document);\n }\n });\n observer.observe(document.documentElement, { childList: true, subtree: true, attributes: true, attributeFilter: ['src'] });\n } catch (e) {}\n }\n\n if (typeof document !== 'undefined') {\n if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start, false);\n else start();\n }\n window.addEventListener('message', onMessage, false);\n})();\n</script>"
},
{
"type": "BOOLEAN",
diff --git a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-contact-form-7.json b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-contact-form-7.json
index 1905480..854f067 100644
--- a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-contact-form-7.json
+++ b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-contact-form-7.json
@@ -29,7 +29,7 @@
{
"type": "TEMPLATE",
"key": "html",
- "value": "<script>\n(function () {\n if (window.__ctDetectContactForm7) return;\n window.__ctDetectContactForm7 = true;\n window.dataLayer = window.dataLayer || [];\n\n function fireConversion(formEl) {\n // Modern Contact Form 7 (verified against 6.1.6 on a live site) puts\n // data-wpcf7-id on the WRAPPING <div class=\"wpcf7\">, not on the <form>\n // element itself. Check the form first (older/other CF7 setups may\n // still stamp it there) and fall back to the wrapper.\n var formId = '';\n try {\n if (formEl && formEl.getAttribute) {\n formId = formEl.getAttribute('data-wpcf7-id') || '';\n }\n if (!formId && formEl && formEl.closest) {\n var wrap = formEl.closest('.wpcf7');\n if (wrap && wrap.getAttribute) {\n formId = wrap.getAttribute('data-wpcf7-id') || '';\n }\n }\n } catch (e) {\n // .closest unsupported in very old browsers — non-fatal, form_id stays ''\n }\n window.dataLayer.push({\n event: 'contact_form_7_submitted',\n form_id: formId\n });\n }\n\n // Fire path — Contact Form 7's own native DOM CustomEvent, dispatched on\n // the <form> element once an AJAX submission passes CF7's server-side\n // validation and spam checks, then bubbles to document. This is the ONLY\n // path this recipe tracks; a legacy non-AJAX (full page reload) CF7 setup\n // never dispatches this event at all — CF7 itself provides no client-side\n // success signal in that mode either (the real module only logs a\n // warning for it, it never fires a conversion).\n document.addEventListener('wpcf7mailsent', function (event) {\n var formEl = event && event.target;\n if (!formEl || (formEl.tagName || '').toLowerCase() !== 'form') return;\n fireConversion(formEl);\n }, false);\n})();\n</script>"
+ "value": "<script>\n(function () {\n 'use strict';\n\n // One shared runtime owns eligibility, accepted event identity, and the ID-only fallback.\n // A legacy recipe guard without this runtime is unknown code, so do not stack a new listener.\n var runtime = window.__ctCf7Runtime;\n if (runtime && runtime.installed) return;\n if (!runtime && window.__ctDetectContactForm7) return;\n runtime = runtime || { installed: false };\n window.__ctCf7Runtime = runtime;\n window.__ctDetectContactForm7 = true;\n window.dataLayer = window.dataLayer || [];\n var seenEvents = typeof WeakSet === 'function' ? new WeakSet() : null;\n var seenEventFallback = [];\n\n function isContactForm7Form(formEl) {\n if (!formEl || (formEl.tagName || '').toLowerCase() !== 'form') return false;\n try {\n if (formEl.classList && formEl.classList.contains('wpcf7-form')) return true;\n return !!(formEl.closest && formEl.closest('.wpcf7'));\n } catch (e) {\n return false;\n }\n }\n\n function validFormId(value) {\n if (typeof value === 'number' && Number.isFinite(value) && Math.floor(value) === value && value > 0 && value <= 9007199254740991) return String(value);\n if (typeof value !== 'string' || !/^[1-9]\\d*$/.test(value)) return '';\n var number = Number(value);\n return Number.isFinite(number) && number <= 9007199254740991 && String(number) === value ? value : '';\n }\n\n function readFormId(formEl, event) {\n // CF7 6.1.6's event detail has contactFormId; read no other detail keys.\n var detailId = '';\n try {\n detailId = validFormId(event && event.detail && event.detail.contactFormId);\n } catch (e) {}\n if (detailId) return detailId;\n\n // Compatibility fallback for markup where the event detail omits the ID.\n try {\n var directId = validFormId(formEl.getAttribute && formEl.getAttribute('data-wpcf7-id'));\n if (directId) return directId;\n var wrap = formEl.closest && formEl.closest('.wpcf7');\n return validFormId(wrap && wrap.getAttribute && wrap.getAttribute('data-wpcf7-id'));\n } catch (e) {\n return '';\n }\n }\n\n // CF7 can send both clicks while the first request is still pending.\n // Group those requests without blocking or changing the form submission.\n document.addEventListener('wpcf7beforesubmit', function (event) {\n var formEl = event && event.target;\n if (!isContactForm7Form(formEl)) return;\n if (!formEl.__ctCf7Attempt || formEl.getAttribute('data-status') !== 'submitting') {\n formEl.__ctCf7Attempt = { emitted: false };\n }\n }, false);\n\n document.addEventListener('wpcf7mailsent', function (event) {\n var formEl = event && event.target;\n if (!isContactForm7Form(formEl)) return;\n if (seenEvents) {\n if (seenEvents.has(event)) return;\n seenEvents.add(event);\n } else {\n if (seenEventFallback.indexOf(event) !== -1) return;\n seenEventFallback.push(event);\n if (seenEventFallback.length > 50) seenEventFallback.shift();\n }\n\n var formId = readFormId(formEl, event);\n if (!formId) return;\n var attempt = formEl.__ctCf7Attempt;\n if (attempt && attempt.emitted) return;\n if (attempt) attempt.emitted = true;\n\n // The optional Method 2 adapter may enrich this accepted event. It must\n // return literal true only after pushing; otherwise the shared core emits\n // the same event with IDs only. Neither path inspects event.detail values.\n var enriched = false;\n try {\n if (typeof window.__ctCf7Method2Emit === 'function') {\n enriched = window.__ctCf7Method2Emit(formEl, event, formId) === true;\n }\n } catch (e) {\n enriched = false;\n }\n if (!enriched) {\n window.dataLayer.push({ event: 'contact_form_7_submitted', form_id: formId });\n }\n }, false);\n runtime.installed = true;\n})();\n</script>"
},
{
"type": "BOOLEAN",
@@ -100,4 +100,4 @@
"fingerprint": "0",
"tagManagerUrl": "https://tagmanager.google.com/#/container/accounts/0/containers/0/workspaces/0"
}
-}
+}
\ No newline at end of file
diff --git a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-divi-forms.json b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-divi-forms.json
index 1eba3f2..258c1dc 100644
--- a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-divi-forms.json
+++ b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-divi-forms.json
@@ -29,7 +29,7 @@
{
"type": "TEMPLATE",
"key": "html",
- "value": "<script>\n(function () {\n if (window.__ctDetectDiviForms) return;\n window.__ctDetectDiviForms = true;\n window.dataLayer = window.dataLayer || [];\n\n // Real id if the container has one, else a synthetic per-page-load key\n // stamped onto it \u2014 ported directly from the production module's\n // getFormKey helper, so multiple Divi forms on one page stay distinct.\n var keyCounter = 0;\n\n function getFormKey(container) {\n if (!container) return '';\n if (container.id) return container.id;\n var key = container.getAttribute('data-ct-key');\n if (!key) {\n keyCounter++;\n key = 'divi-' + keyCounter;\n container.setAttribute('data-ct-key', key);\n }\n return key;\n }\n\n function fireConversion(formId) {\n window.dataLayer.push({\n event: 'divi_form_submitted',\n form_id: formId || ''\n });\n }\n\n // Divi renders BOTH validation errors and the success notice into\n // .et-pb-contact-message \u2014 the element itself carries no success/error\n // marker. Errors mark the offending inputs with .et_contact_error and\n // wrap the message text in .et_pb_contact_error_text. Only fire when\n // the message has text and no error markers are present.\n function maybeReportSuccess(container) {\n if (!container || !container.querySelector) return;\n\n var msg = container.querySelector('.et-pb-contact-message');\n if (!msg) return;\n\n var text = (msg.textContent || '').trim();\n if (!text) return;\n\n try {\n if (msg.querySelector('.et_pb_contact_error_text')) return;\n if (container.querySelector('.et_contact_error')) return;\n } catch (e) {\n // Can't tell success from error \u2014 do not fire\n return;\n }\n\n // Permanent stamp: long-tail mutations of the container (other\n // plugins, widgets) must not re-report a message that already fired\n if (msg.getAttribute('data-ct-reported') === 'true') return;\n msg.setAttribute('data-ct-reported', 'true');\n\n fireConversion(getFormKey(container));\n }\n\n function observeContainer(container) {\n if (typeof MutationObserver === 'undefined') return;\n if (!container || !container.getAttribute) return;\n if (container.getAttribute('data-ct-observed') === 'true') return;\n container.setAttribute('data-ct-observed', 'true');\n\n var observer = new MutationObserver(function () {\n maybeReportSuccess(container);\n });\n\n observer.observe(container, {\n childList: true,\n subtree: true,\n characterData: true\n });\n }\n\n function startMutationObserver() {\n if (typeof MutationObserver === 'undefined') return;\n\n var containers = document.querySelectorAll('.et_pb_contact_form_container');\n for (var c = 0; c < containers.length; c++) {\n observeContainer(containers[c]);\n }\n }\n\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', function () {\n startMutationObserver();\n });\n } else {\n startMutationObserver();\n }\n\n // Also rescan after window load in case Divi loads forms late\n // (observeContainer is idempotent per container)\n window.addEventListener('load', function () {\n startMutationObserver();\n });\n})();\n</script>"
+ "value": "<script>\n(function () {\n if (window.__ctDetectDiviForms) return;\n window.__ctDetectDiviForms = true;\n window.dataLayer = window.dataLayer || [];\n var reported = typeof WeakSet === 'function' ? new WeakSet() : null;\n function inspect(container) {\n if (!container || !container.querySelector) return;\n var notice;\n try {\n notice = container.querySelector('.et-pb-contact-message.et_pb_success_message');\n if (!notice || container.querySelector('form.et_pb_contact_form') ||\n container.querySelector('.et_pb_contact_error_meesage') ||\n container.querySelector('.et_contact_error')) return;\n } catch (e) { return; }\n if (reported && reported.has(notice)) return;\n if (reported) reported.add(notice);\n var id = container.id || (container.getAttribute && container.getAttribute('data-id')) || '';\n if (!id) return;\n var adapter = window.__ctDiviMethod2Emit;\n if (typeof adapter === 'function' && adapter(container, String(id)) === true) return;\n window.dataLayer.push({ event: 'divi_form_submitted', form_id: String(id) });\n }\n function observe(container) {\n if (!container || container.__ctDiviObserved || typeof MutationObserver === 'undefined') return;\n container.__ctDiviObserved = true;\n new MutationObserver(function () { inspect(container); }).observe(container,\n { childList: true, subtree: true, attributes: true, attributeFilter: ['class'] });\n inspect(container);\n }\n function start() {\n var existing = document.querySelectorAll('.et_pb_contact_form_container');\n for (var i = 0; i < existing.length; i++) observe(existing[i]);\n if (typeof MutationObserver !== 'undefined' && document.documentElement) {\n new MutationObserver(function (records) {\n for (var r = 0; r < records.length; r++) {\n for (var n = 0; n < records[r].addedNodes.length; n++) {\n var node = records[r].addedNodes[n];\n if (node.nodeType !== 1) continue;\n if (node.matches && node.matches('.et_pb_contact_form_container')) observe(node);\n var nested = node.querySelectorAll ? node.querySelectorAll('.et_pb_contact_form_container') : [];\n for (var j = 0; j < nested.length; j++) observe(nested[j]);\n }\n }\n }).observe(document.documentElement, { childList: true, subtree: true });\n }\n }\n if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start, { once: true });\n else start();\n})();\n</script>"
},
{
"type": "BOOLEAN",
diff --git a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-elementor-forms.json b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-elementor-forms.json
index a2b296c..7a1afb4 100644
--- a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-elementor-forms.json
+++ b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-elementor-forms.json
@@ -29,7 +29,7 @@
{
"type": "TEMPLATE",
"key": "html",
- "value": "<script>\n(function () {\n if (window.__ctDetectElementorForms) return;\n window.__ctDetectElementorForms = true;\n window.dataLayer = window.dataLayer || [];\n\n // Best-effort, non-PII identifier: the form's own id/name, or the\n // nearest ancestor carrying Elementor's standard data-id widget-instance\n // attribute. Never reads field values.\n function bestEffortFormId(formEl) {\n if (!formEl) return '';\n if (formEl.id) return formEl.id;\n var name = formEl.getAttribute && formEl.getAttribute('name');\n if (name) return name;\n try {\n var withId = formEl.closest && formEl.closest('[data-id]');\n if (withId) return withId.getAttribute('data-id') || '';\n } catch (e) {\n // .closest not available — non-fatal\n }\n return '';\n }\n\n function fireConversion(formId) {\n window.dataLayer.push({\n event: 'elementor_form_submitted',\n form_id: formId || ''\n });\n }\n\n // Same form-resolution chain the production module uses (event.target\n // -> most recently clicked Elementor submit button's form -> the sole\n // .elementor-form on the page) — ported here so the recipe can attach a\n // real form_id instead of firing event-only.\n var lastClickedForm = null;\n\n function trackClick(event) {\n try {\n var target = event.target;\n if (!target || !target.closest) return;\n var form = target.closest('form.elementor-form');\n if (form) lastClickedForm = form;\n } catch (e) {\n // non-fatal\n }\n }\n\n function resolveFormFromTarget(target) {\n if (!target || target === document || target === window) return null;\n try {\n if ((target.tagName || '').toLowerCase() === 'form' &&\n target.classList && target.classList.contains('elementor-form')) {\n return target;\n }\n if (target.closest) {\n var parentForm = target.closest('form.elementor-form');\n if (parentForm) return parentForm;\n }\n } catch (e) {\n // non-fatal\n }\n return null;\n }\n\n // Fire path — Elementor Pro's own jQuery event, triggered on `document`\n // once an AJAX submission passes server-side validation. This is the ONLY\n // path this recipe tracks; Elementor Pro forms submit exclusively via\n // Elementor's own AJAX pipeline, so there is no non-AJAX mode to miss.\n var successHooked = false;\n\n function hookElementorSuccess() {\n if (successHooked) return true;\n // A bare $ is only trusted when it looks like jQuery ($.fn exists), so\n // another library that claims $ cannot break the hook.\n var jQ = null;\n if (typeof jQuery !== 'undefined') jQ = jQuery;\n else if (typeof $ !== 'undefined' && typeof $.fn !== 'undefined') jQ = $;\n if (!jQ) return false;\n jQ(document).on('submit_success', function (event) {\n var formEl = resolveFormFromTarget(event && event.target);\n if (!formEl && lastClickedForm) formEl = lastClickedForm;\n lastClickedForm = null;\n\n if (!formEl) {\n try {\n var forms = document.querySelectorAll('.elementor-form');\n if (forms.length === 1) formEl = forms[0];\n } catch (e) {\n // non-fatal\n }\n }\n\n fireConversion(bestEffortFormId(formEl));\n });\n successHooked = true;\n return true;\n }\n\n document.addEventListener('click', trackClick, true);\n\n if (!hookElementorSuccess()) {\n document.addEventListener('DOMContentLoaded', function () {\n hookElementorSuccess();\n });\n window.addEventListener('load', function () {\n hookElementorSuccess();\n });\n }\n})();\n</script>"
+ "value": "<script>\n(function () {\n if (window.__ctDetectElementorForms) return;\n window.__ctDetectElementorForms = true;\n window.dataLayer = window.dataLayer || [];\n var seenEvents = typeof WeakSet === 'function' ? new WeakSet() : null;\n function formFrom(target) {\n try {\n if (!target || target === document || target === window) return null;\n if (target.matches && target.matches('form.elementor-form')) return target;\n return target.closest ? target.closest('form.elementor-form') : null;\n } catch (e) { return null; }\n }\n function formId(form) {\n if (!form) return '';\n if (form.id) return form.id;\n var name = form.getAttribute && form.getAttribute('name');\n if (name && name !== 'New Form') return name;\n var widget = form.closest && form.closest('[data-id]');\n return widget && widget.getAttribute('data-id') || '';\n }\n function onSuccess(event) {\n if (event && seenEvents) {\n if (seenEvents.has(event)) return;\n seenEvents.add(event);\n }\n var form = formFrom(event && event.target);\n var id = formId(form);\n if (!form || !id) return;\n var adapter = window.__ctElementorMethod2Emit;\n if (typeof adapter === 'function') {\n try { if (adapter(form, id) === true) return; }\n catch (e) { return; }\n }\n window.dataLayer.push({ event: 'elementor_form_submitted', form_id: String(id) });\n }\n var handlerBound = false;\n function hook() {\n if (handlerBound) return true;\n var jq = typeof jQuery !== 'undefined' ? jQuery : (typeof $ !== 'undefined' ? $ : null);\n if (!jq) return false;\n jq(document).on('submit_success', onSuccess);\n handlerBound = true;\n return true;\n }\n if (!hook()) {\n document.addEventListener('DOMContentLoaded', hook, { once: true });\n window.addEventListener('load', hook, { once: true });\n }\n})();\n</script>"
},
{
"type": "BOOLEAN",
@@ -100,4 +100,4 @@
"fingerprint": "0",
"tagManagerUrl": "https://tagmanager.google.com/#/container/accounts/0/containers/0/workspaces/0"
}
-}
+}
\ No newline at end of file
diff --git a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-fluent-forms.json b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-fluent-forms.json
index 9653143..42d3b21 100644
--- a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-fluent-forms.json
+++ b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-fluent-forms.json
@@ -29,7 +29,7 @@
{
"type": "TEMPLATE",
"key": "html",
- "value": "<script>\n(function () {\n if (window.__ctDetectFluentForms) return;\n window.__ctDetectFluentForms = true;\n window.dataLayer = window.dataLayer || [];\n\n function isFluentForm(formEl) {\n if (!formEl) return false;\n if (formEl.className && formEl.className.indexOf('frm-fluent-form') !== -1) return true;\n try {\n if (formEl.closest && formEl.closest('.fluentform')) return true;\n } catch (e) {\n // .closest not available \u2014 fall back to ID check\n }\n var id = formEl.id || '';\n return /^fluentform_\\d+$/.test(id);\n }\n\n // Accepts a jQuery object or a DOM element; returns the underlying DOM\n // element if it is a Fluent Forms <form>, else null.\n function asFluentForm(candidate) {\n if (!candidate) return null;\n var el = candidate;\n if (el.jquery && el.length) el = el[0]; // unwrap jQuery objects only \u2014\n // never plain elements: form[0] on a raw <form> is its first control.\n if ((el.tagName || '').toLowerCase() === 'form' && isFluentForm(el)) return el;\n return null;\n }\n\n // Click-tracking fallback for form attribution: remember the Fluent form\n // whose submit button was most recently clicked, in case an old Fluent\n // Forms version fires the success event without a form reference.\n var lastActiveForm = null;\n\n function trackSubmitClick(event) {\n try {\n var target = event.target;\n if (!target || !target.closest) return;\n var btn = target.closest('.ff-btn-submit');\n if (!btn) return;\n var form = btn.closest('form');\n if (form && isFluentForm(form)) lastActiveForm = form;\n } catch (e) {\n // non-fatal\n }\n }\n\n // Resolution order (first valid Fluent form wins) \u2014 live-verified against\n // Fluent Forms 6.2.5, 2026-07-05:\n // 1. data.form from the handler's data argument \u2014 the <body> dispatch\n // passes { form, config, response } where form is the jQuery-wrapped\n // form (also accept data itself being the form, defensively)\n // 2. event.originalEvent.detail.form \u2014 the native CustomEvent dispatch\n // carries the raw form element in detail\n // 3. event.target, if it IS a Fluent form (direct-on-form re-trigger)\n // 4. the form whose submit button was most recently clicked\n // 5. the only .frm-fluent-form on the page, if exactly one exists\n function resolveSuccessForm(event, data) {\n var el = asFluentForm(data && data.form) || asFluentForm(data);\n if (el) return el;\n\n try {\n var oe = event && event.originalEvent;\n if (oe && oe.detail) {\n el = asFluentForm(oe.detail.form);\n if (el) return el;\n }\n } catch (e) {\n // originalEvent/detail unreadable \u2014 keep falling back\n }\n\n el = asFluentForm(event && event.target);\n if (el) return el;\n\n if (lastActiveForm && document.contains(lastActiveForm) && isFluentForm(lastActiveForm)) {\n return lastActiveForm;\n }\n\n try {\n var forms = document.querySelectorAll('.frm-fluent-form');\n if (forms.length === 1) return forms[0];\n } catch (e) {\n // querySelectorAll unavailable \u2014 give up\n }\n\n return null;\n }\n\n // Dedup: one successful submission reaches a document-level jQuery\n // listener TWICE on current Fluent Forms (the jQuery <body> trigger and\n // the native CustomEvent) \u2014 verified live. Both duplicates resolve to the\n // same form within the same tick, so fire once per form per 2s window\n // (matches production listener behaviour). Rapid legitimate\n // re-submissions of the same form take well over 2s (server round trip +\n // success render), so none are lost.\n var lastFiredForm = null;\n var lastFiredAt = 0;\n\n function fireConversion(formEl) {\n var now = new Date().getTime();\n if (lastFiredForm === formEl && now - lastFiredAt < 2000) return;\n lastFiredForm = formEl;\n lastFiredAt = now;\n window.dataLayer.push({\n event: 'fluent_forms_submitted',\n form_id: (formEl && formEl.id) || ''\n });\n }\n\n // Fire path \u2014 Fluent Forms' success signal, fired once an AJAX submission\n // passes server-side validation. This is the ONLY path this recipe\n // tracks; Fluent Forms always submits via AJAX (there is no non-AJAX\n // mode to miss). Client-side validation failures, native HTML5 blocks,\n // and server-side rejections never fire it. Hooked via jQuery because\n // the <body> dispatch is jQuery-only AND jQuery is guaranteed on any\n // working Fluent Forms page (Fluent Forms' own submission handler\n // requires it \u2014 without jQuery the form cannot submit at all).\n var successHooked = false;\n\n function hookFluentSuccess() {\n if (successHooked) return true;\n if (typeof window.jQuery === 'undefined') return false;\n\n window.jQuery(document).on('fluentform_submission_success', function (event, data) {\n fireConversion(resolveSuccessForm(event, data));\n });\n successHooked = true;\n return true;\n }\n\n document.addEventListener('click', trackSubmitClick, true);\n\n if (!hookFluentSuccess()) {\n document.addEventListener('DOMContentLoaded', function () {\n hookFluentSuccess();\n });\n window.addEventListener('load', function () {\n hookFluentSuccess();\n });\n }\n})();\n</script>"
+ "value": "<script>\n(function () {\n if (window.__ctFluentForms) return;\n window.__ctFluentForms = true;\n window.dataLayer = window.dataLayer || [];\n var listeners = [], lastEvent = null;\n // Fluent Forms 6.2.5 reports one success response through three different\n // event objects. Deduplicate by response-object identity and original form\n // node; never inspect or retain a response's fields.\n var seenResponses = typeof WeakMap === 'function' ? new WeakMap() : null;\n window.__ctFluentSubscribe = function (listener) {\n if (listener && typeof listener === 'object') listeners.push(listener);\n };\n function isForm(form) {\n try {\n if (!form || String(form.tagName || '').toLowerCase() !== 'form') return false;\n if (String(form.className || '').indexOf('frm-fluent-form') !== -1) return true;\n if (form.closest && form.closest('.fluentform')) return true;\n return /^fluentform_\\d+$/.test(form.id || '');\n } catch (e) { return false; }\n }\n function asForm(candidate) {\n try {\n var el = candidate;\n if (el && el.jquery && el.length) el = el[0];\n return isForm(el) ? el : null;\n } catch (e) { return null; }\n }\n function notify(phase, form, candidate, event, arg2, arg3) {\n var handled = false;\n for (var i=0;i<listeners.length;i++) {\n try { var fn=listeners[i] && listeners[i][phase]; if(typeof fn==='function' && fn(form,candidate,event,arg2,arg3)===true)handled=true; } catch(e) {}\n }\n return handled;\n }\n function submit(event) {\n try { var form=event.target; if(isForm(form)) notify('beforeAttempt',form,false,event); } catch(e) {}\n }\n function resolve(event,arg2,arg3) {\n try {\n var form=asForm(arg2 && arg2.form) || asForm(arg3) || asForm(arg2);\n if(form)return form;\n var oe=event && event.originalEvent;\n if(oe && oe.detail) return asForm(oe.detail.form);\n return asForm(event && event.target);\n } catch(e) { return null; }\n }\n function responseFor(event, arg2) {\n try {\n var descriptor = arg2 && Object.getOwnPropertyDescriptor(arg2, 'response');\n var response = descriptor && Object.prototype.hasOwnProperty.call(descriptor, 'value') ? descriptor.value : null;\n if (response && typeof response === 'object') return response;\n var originalEvent = event && event.originalEvent;\n var detail = originalEvent && originalEvent.detail;\n descriptor = detail && Object.getOwnPropertyDescriptor(detail, 'response');\n response = descriptor && Object.prototype.hasOwnProperty.call(descriptor, 'value') ? descriptor.value : null;\n return response && typeof response === 'object' ? response : null;\n } catch(e) { return null; }\n }\n function alreadySeen(response, form) {\n try {\n if (!seenResponses || !response || !form || typeof response !== 'object' || typeof form !== 'object') return true;\n var forms = seenResponses.get(response);\n if (!forms) {\n forms = typeof WeakSet === 'function' ? new WeakSet() : null;\n if (!forms) return true;\n seenResponses.set(response, forms);\n }\n if (forms.has(form)) return true;\n forms.add(form);\n return false;\n } catch(e) { return true; }\n }\n function success(event,arg2,arg3) {\n try {\n if (event && typeof event === 'object' && event === lastEvent) return;\n lastEvent=event;\n if (event && typeof event === 'object') setTimeout(function(){if(lastEvent===event)lastEvent=null;},0);\n var form=resolve(event,arg2,arg3);\n if(!form)return;\n var response=responseFor(event,arg2);\n if(!response || alreadySeen(response,form))return;\n if(!notify('onCandidate',form,true,event,arg2,arg3)) window.dataLayer.push({event:'fluent_forms_submitted',form_id:form.id || ''});\n } catch(e) {}\n }\n document.addEventListener('submit',submit,true);\n function hook() {\n try {\n if (window.__ctFluentSuccessHooked || !window.jQuery) return false;\n window.__ctFluentSuccessHooked=true;\n window.jQuery(document).on('fluentform_submission_success',success);\n return true;\n } catch(e) { return false; }\n }\n if(!hook()) {\n document.addEventListener('DOMContentLoaded',hook);\n window.addEventListener('load',hook);\n }\n})();\n</script>"
},
{
"type": "BOOLEAN",
diff --git a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-formidable-forms.json b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-formidable-forms.json
index ef8e53e..5e748c3 100644
--- a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-formidable-forms.json
+++ b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-formidable-forms.json
@@ -29,7 +29,7 @@
{
"type": "TEMPLATE",
"key": "html",
- "value": "<script>\n(function () {\n if (window.__ctDetectFormidableForms) return;\n window.__ctDetectFormidableForms = true;\n window.dataLayer = window.dataLayer || [];\n\n var SUCCESS_WINDOW_MS = 10000;\n var DEFERRED_MARKER_KEY = '__ctDetectFormidableNativePending';\n var DEFERRED_MARKER_TTL_MS = 60000;\n\n function isFormidableForm(formEl) {\n if (!formEl) return false;\n try {\n if (formEl.closest && formEl.closest('.frm_forms')) return true;\n } catch (e) {\n // .closest not available \u2014 fall back to class check\n }\n var cls = ' ' + (formEl.className || '') + ' ';\n return cls.indexOf(' frm-show-form ') !== -1;\n }\n\n function fireConversion(formId, formEl) {\n // Both AJAX events (and the native path) can resolve to the same\n // submission \u2014 dedupe with a short-lived flag on the form when it's\n // resolvable. If it isn't resolvable we still fire (favors counting a\n // real submission over silently dropping it).\n if (!formEl && formId) formEl = document.getElementById('form_' + formId);\n if (formEl) {\n if (formEl.getAttribute('data-ct-processing') === 'true') return;\n formEl.setAttribute('data-ct-processing', 'true');\n setTimeout(function () { formEl.removeAttribute('data-ct-processing'); }, 2000);\n disarmWatcher(formEl);\n }\n window.dataLayer.push({\n event: 'formidable_forms_submitted',\n form_id: formId || ''\n });\n }\n\n // ---- Shared validation-marker check (used by both fire paths) ----\n\n function isNodeHidden(el) {\n try {\n if (el.hidden) return true;\n if (el.getAttribute && el.getAttribute('aria-hidden') === 'true') return true;\n var view = el.ownerDocument && el.ownerDocument.defaultView;\n if (view && view.getComputedStyle) {\n var cs = view.getComputedStyle(el);\n if (cs && (cs.display === 'none' || cs.visibility === 'hidden')) return true;\n }\n } catch (e) {\n // fall through\n }\n return false;\n }\n\n // Formidable's standard error markers: .frm_error (per-field message),\n // .frm_error_style (form-level rejection box), .frm_blank_field (state\n // class on a required-but-blank field), [aria-invalid=\"true\"].\n function hasVisibleValidationErrors(scopeEl) {\n if (!scopeEl || !scopeEl.querySelectorAll) return false;\n try {\n var nodes = scopeEl.querySelectorAll(\n '.frm_error, .frm_error_style, .frm_blank_field, [aria-invalid=\"true\"]'\n );\n for (var i = 0; i < nodes.length; i++) {\n var node = nodes[i];\n if (isNodeHidden(node)) continue;\n if (node.getAttribute && node.getAttribute('aria-invalid') === 'true') return true;\n var cls = ' ' + (typeof node.className === 'string' ? node.className : '') + ' ';\n if (cls.indexOf(' frm_blank_field ') !== -1) return true;\n if ((node.textContent || '').trim()) return true;\n }\n } catch (e) {\n // fall through\n }\n return false;\n }\n\n function hasServerRejectionMarkers() {\n try {\n var wrappers = document.querySelectorAll('.frm_forms');\n for (var i = 0; i < wrappers.length; i++) {\n if (hasVisibleValidationErrors(wrappers[i])) return true;\n }\n } catch (e) {\n // fall through\n }\n return false;\n }\n\n function hasSuccessMessage() {\n try {\n var nodes = document.querySelectorAll('.frm_message');\n for (var i = 0; i < nodes.length; i++) {\n if (isNodeHidden(nodes[i])) continue;\n if ((nodes[i].textContent || '').trim()) return true;\n }\n } catch (e) {\n // fall through\n }\n return false;\n }\n\n // ---- Fire path 1: AJAX success events ----\n\n var activeWatchers = [];\n\n function findWatcher(formEl) {\n for (var w = 0; w < activeWatchers.length; w++) {\n if (activeWatchers[w].form === formEl) return activeWatchers[w];\n }\n return null;\n }\n\n function disarmWatcher(formEl) {\n var existing = findWatcher(formEl);\n if (existing && typeof existing.cleanup === 'function') existing.cleanup();\n }\n\n function handleAjaxSuccessEvent(event) {\n var formId = '';\n try {\n if (event.detail && event.detail.frmVars && event.detail.frmVars.formID) {\n formId = event.detail.frmVars.formID;\n }\n } catch (e) {\n // detail not available\n }\n\n var formEl = formId ? document.getElementById('form_' + formId) : null;\n if (!formEl) {\n // Fallback: the first form inside the first .frm_forms wrapper.\n try {\n var wrappers = document.querySelectorAll('.frm_forms');\n for (var i = 0; i < wrappers.length; i++) {\n var f = wrappers[i].querySelector('form');\n if (f) { formEl = f; break; }\n }\n } catch (e) {\n // querySelectorAll unavailable \u2014 give up\n }\n }\n\n fireConversion(formId, formEl);\n }\n\n // ---- Fire path 2: native (non-AJAX) pagehide watcher + deferred verdict ----\n\n function writeDeferredMarker(formId) {\n try {\n window.sessionStorage.setItem(DEFERRED_MARKER_KEY, JSON.stringify({\n t: Date.now(),\n path: window.location.pathname,\n formId: formId\n }));\n return true;\n } catch (e) {\n return false;\n }\n }\n\n function takeDeferredMarker() {\n try {\n var raw = window.sessionStorage.getItem(DEFERRED_MARKER_KEY);\n if (!raw) return null;\n window.sessionStorage.removeItem(DEFERRED_MARKER_KEY);\n var data = JSON.parse(raw);\n if (!data || typeof data !== 'object') return null;\n if (!data.t || Date.now() - data.t > DEFERRED_MARKER_TTL_MS) return null;\n return data;\n } catch (e) {\n try { window.sessionStorage.removeItem(DEFERRED_MARKER_KEY); } catch (e2) {}\n return null;\n }\n }\n\n // Runs once at module init on every page load. Consumes the marker the\n // previous page wrote at pagehide (if any) and reads the verdict from the\n // markup Formidable rendered into THIS page. Rejection is checked first:\n // the rejected-POST re-render always carries error markers, so a missed\n // fire here degrades to under-counting, never fabricating.\n function processDeferredVerdict() {\n var marker = takeDeferredMarker();\n if (!marker) return;\n\n if (hasServerRejectionMarkers()) return;\n\n if (hasSuccessMessage()) {\n fireConversion(marker.formId, null);\n return;\n }\n // No Formidable markup either way. A success configured to redirect\n // lands on a different path with no .frm_message \u2014 treat a changed\n // pathname as that redirect. A rejection can't look like this: the\n // rejected POST always re-renders the form WITH error markers.\n if (marker.path && window.location.pathname !== marker.path) {\n fireConversion(marker.formId, null);\n }\n // Same page, no markers either way \u2014 ambiguous, do not fire.\n }\n\n function armNativeWatcher(formEl, formId, pagehideTrusted) {\n var existing = findWatcher(formEl);\n if (existing) {\n existing.refresh(formId, pagehideTrusted);\n return;\n }\n\n var entry = { form: formEl, refresh: refresh, cleanup: cleanup };\n activeWatchers.push(entry);\n\n var fired = false;\n var timer = null;\n var pagehideArmed = false;\n\n function onPageHide() {\n if (fired) return;\n // Click-then-leave guard: a visitor blocked by Formidable's own\n // validation who then navigates away must not count.\n if (hasVisibleValidationErrors(formEl)) return;\n fired = true;\n if (formEl.getAttribute('data-ct-processing') !== 'true') {\n writeDeferredMarker(formId);\n }\n cleanup();\n }\n\n function armPagehide() {\n if (pagehideArmed) return;\n try {\n window.addEventListener('pagehide', onPageHide, true);\n pagehideArmed = true;\n } catch (e) {\n // fall through\n }\n }\n\n function disarmPagehide() {\n if (!pagehideArmed) return;\n try { window.removeEventListener('pagehide', onPageHide, true); } catch (e) {}\n pagehideArmed = false;\n }\n\n function startTimer() {\n if (timer) clearTimeout(timer);\n timer = setTimeout(function () {\n if (!fired) cleanup();\n }, SUCCESS_WINDOW_MS);\n }\n\n function cleanup() {\n if (timer) { clearTimeout(timer); timer = null; }\n disarmPagehide();\n var idx = activeWatchers.indexOf(entry);\n if (idx !== -1) activeWatchers.splice(idx, 1);\n }\n\n // A later submit on the same form: the visitor corrected a failed\n // field and re-submitted. Refresh everything to the latest attempt.\n function refresh(nextFormId, nextPagehideTrusted) {\n if (fired) return;\n formId = nextFormId;\n if (nextPagehideTrusted) armPagehide();\n else disarmPagehide();\n startTimer();\n }\n\n if (pagehideTrusted) armPagehide();\n startTimer();\n }\n\n // Bubble-phase submit listener \u2014 arms the native watcher on every\n // Formidable submit attempt. This fires even when Formidable\n // preventDefaults it (the event still dispatches) \u2014 this is the moment\n // we snapshot, NOT the moment we fire.\n function handleNativeSubmit(event) {\n var formEl = event.target;\n if (!formEl || (formEl.tagName || '').toLowerCase() !== 'form') return;\n if (!isFormidableForm(formEl)) return;\n\n var formId = '';\n var m = /^form_(\\d+)$/.exec(formEl.id || '');\n if (m) formId = m[1];\n\n // Client-validity gate: trust the pagehide path when the form is valid\n // (or checkValidity is unavailable). NOTE per the source module:\n // Formidable's required-ness is often enforced only server-side, so a\n // form can pass checkValidity() while still blank \u2014 the pagehide-time\n // visible-error check is the real safety net here, not this gate alone.\n var pagehideTrusted = true;\n try {\n if (typeof formEl.checkValidity === 'function' && formEl.checkValidity() === false) {\n pagehideTrusted = false;\n }\n } catch (e) {\n // constraint validation unavailable \u2014 pagehide's visible-error check\n // still guards this path\n }\n\n armNativeWatcher(formEl, formId, pagehideTrusted);\n }\n\n document.addEventListener('frmFormComplete', handleAjaxSuccessEvent, true);\n document.addEventListener('frmBeforeFormRedirect', handleAjaxSuccessEvent, true);\n document.addEventListener('submit', handleNativeSubmit, false);\n\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', function () {\n processDeferredVerdict();\n });\n } else {\n processDeferredVerdict();\n }\n})();\n</script>"
+ "value": "<script>\n(function () {\n 'use strict';\n\n // Shared with the recipe snippet so template + recipe installation is one listener.\n if (window.__ctDetectFormidableForms) return;\n window.__ctDetectFormidableForms = true;\n if (!/^https?:$/.test(window.location.protocol)) return;\n window.dataLayer = window.dataLayer || [];\n\n var MARKER_KEY = '__ctDetectFormidableNativePendingV2';\n var MARKER_TTL_MS = 60000;\n var handledResponses = typeof WeakSet === 'function' ? new WeakSet() : [];\n var activeAttempts = [];\n var jqueryHooked = false;\n\n function safeId(value) {\n var id = String(value || '');\n return /^[1-9][0-9]*$/.test(id) ? id : '';\n }\n\n // Formidable's hidden form_id is non-sensitive structural metadata. No other\n // field value, response property, label, HTML, or rendered text is inspected.\n function formId(form) {\n if (!form || typeof form.querySelector !== 'function') return '';\n try {\n var input = form.querySelector('input[name=\"form_id\"]');\n return input && input.getAttribute ? safeId(input.getAttribute('value')) : '';\n } catch (e) {\n return '';\n }\n }\n\n function wrapperFor(id) {\n if (!id) return null;\n try { return document.getElementById('frm_form_' + id + '_container'); } catch (e) { return null; }\n }\n\n function hasNode(scope, selector) {\n if (!scope || typeof scope.querySelector !== 'function') return false;\n try { return !!scope.querySelector(selector); } catch (e) { return false; }\n }\n\n function hasRejectionMarker(id) {\n return hasNode(wrapperFor(id), '.frm_error, .frm_error_style, .frm_blank_field, [aria-invalid=\"true\"]');\n }\n\n function hasSuccessMarker(id) {\n return hasNode(wrapperFor(id), '.frm_message');\n }\n\n function responseWasHandled(response) {\n if (!response || (typeof response !== 'object' && typeof response !== 'function')) return true;\n if (typeof WeakSet === 'function' && handledResponses instanceof WeakSet) {\n if (handledResponses.has(response)) return true;\n handledResponses.add(response);\n return false;\n }\n for (var i = 0; i < handledResponses.length; i++) {\n if (handledResponses[i] === response) return true;\n }\n handledResponses.push(response);\n if (handledResponses.length > 100) handledResponses.shift();\n return false;\n }\n\n function push(id) {\n if (!id) return;\n window.dataLayer.push({ event: 'formidable_forms_submitted', form_id: id });\n }\n\n // Optional Method 2 adapter owns any enriched push. The detector passes only\n // structural metadata and accepts only a literal true handled verdict; it\n // never receives or inspects an adapter payload.\n function emitAccepted(id, form, source) {\n var handled = false;\n try {\n if (typeof window.__ctFormidableMethod2Emit === 'function') {\n handled = window.__ctFormidableMethod2Emit(id, form, source) === true;\n }\n } catch (e) {}\n if (!handled) push(id);\n }\n\n // In 6.32.1 these are jQuery events: formidable.js calls\n // jQuery(document).trigger(name, [form, response]). addEventListener does not\n // receive these success events. The response is used only by object identity\n // so the redirect and completion callbacks for one response count once.\n function onAjaxSuccess(event, form, response) {\n var id = formId(form);\n if (!id || !response || responseWasHandled(response)) return;\n emitAccepted(id, form, 'ajax');\n disarmAttempt(form);\n }\n\n function hookJquery() {\n if (jqueryHooked) return true;\n var jq = window.jQuery || window.$;\n if (typeof jq !== 'function') return false;\n jq(document).on(\n 'frmFormComplete.ctRecipe frmBeforeFormRedirect.ctRecipe',\n onAjaxSuccess\n );\n jqueryHooked = true;\n return true;\n }\n\n function readMarker() {\n try {\n var raw = window.sessionStorage.getItem(MARKER_KEY);\n if (!raw) return null;\n window.sessionStorage.removeItem(MARKER_KEY);\n var marker = JSON.parse(raw);\n if (!marker || typeof marker !== 'object') return null;\n if (typeof marker.t !== 'number' || Date.now() < marker.t || Date.now() - marker.t > MARKER_TTL_MS) return null;\n if (marker.hadSuccessAtSubmit === true) return null;\n return { id: safeId(marker.id), origin: marker.origin, path: marker.path };\n } catch (e) {\n try { window.sessionStorage.removeItem(MARKER_KEY); } catch (e2) {}\n return null;\n }\n }\n\n // Native success either renders a form-specific message or redirects away\n // from the submitted form. Rejection stays on the form page with errors.\n // Only origin and pathname are retained, never query strings or form answers.\n function processNativeMessage() {\n var marker = readMarker();\n if (!marker || !marker.id || hasRejectionMarker(marker.id)) return;\n var redirected = marker.origin === window.location.origin &&\n typeof marker.path === 'string' && marker.path !== window.location.pathname &&\n !wrapperFor(marker.id) && !hasNode(document, '.frm_error, .frm_error_style');\n if (hasSuccessMarker(marker.id) || redirected) {\n var wrapper = wrapperFor(marker.id);\n var form = null;\n try { form = wrapper && wrapper.querySelector ? wrapper.querySelector('form') : null; } catch (e) {}\n emitAccepted(marker.id, form, 'native');\n }\n }\n\n function getAttempt(form) {\n for (var i = 0; i < activeAttempts.length; i++) {\n if (activeAttempts[i].form === form) return activeAttempts[i];\n }\n return null;\n }\n\n function disarmAttempt(form) {\n var attempt = getAttempt(form);\n if (!attempt) return;\n try { window.removeEventListener('pagehide', attempt.onPageHide, true); } catch (e) {}\n var index = activeAttempts.indexOf(attempt);\n if (index !== -1) activeAttempts.splice(index, 1);\n }\n\n function armNativeMessageAttempt(event) {\n var form = event && event.target;\n if (!form || String(form.tagName || '').toLowerCase() !== 'form') return;\n var isFormidable = false;\n try { isFormidable = !!(form.closest && form.closest('.frm_forms')); } catch (e) {}\n if (!isFormidable) return;\n var id = formId(form);\n if (!id) return;\n var wrapper = wrapperFor(id);\n var hadSuccessAtSubmit = hasNode(wrapper, '.frm_message');\n var prior = getAttempt(form);\n if (prior) disarmAttempt(form);\n var attempt = { form: form, id: id, hadSuccessAtSubmit: hadSuccessAtSubmit, onPageHide: null };\n attempt.onPageHide = function () {\n disarmAttempt(form);\n // Old server errors remain visible while a corrected native POST leaves.\n // Decide acceptance from the response page, not the departing page.\n if (attempt.hadSuccessAtSubmit) return;\n try {\n window.sessionStorage.setItem(MARKER_KEY, JSON.stringify({\n t: Date.now(),\n id: attempt.id,\n hadSuccessAtSubmit: false,\n origin: window.location.origin,\n path: window.location.pathname\n }));\n } catch (e) {}\n };\n activeAttempts.push(attempt);\n try { window.addEventListener('pagehide', attempt.onPageHide, true); } catch (e) {}\n }\n\n hookJquery();\n if (!jqueryHooked) {\n document.addEventListener('DOMContentLoaded', hookJquery, { once: true });\n window.addEventListener('load', hookJquery, { once: true });\n }\n document.addEventListener('submit', armNativeMessageAttempt, true);\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', processNativeMessage, { once: true });\n } else {\n processNativeMessage();\n }\n})();\n</script>"
},
{
"type": "BOOLEAN",
diff --git a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-forminator.json b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-forminator.json
index c1e8437..ac6ffdd 100644
--- a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-forminator.json
+++ b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-forminator.json
@@ -29,7 +29,7 @@
{
"type": "TEMPLATE",
"key": "html",
- "value": "<script>\n(function () {\n if (window.__ctDetectForminator) return;\n window.__ctDetectForminator = true;\n window.dataLayer = window.dataLayer || [];\n\n function fireConversion(formId) {\n window.dataLayer.push({\n event: 'forminator_form_submitted',\n form_id: formId || ''\n });\n }\n\n // Fire path \u2014 Forminator's own jQuery event, fired on `document` once an\n // AJAX submission passes server-side validation. This is the ONLY path\n // that ever fires a conversion; Forminator clears form fields before this\n // event, but we don't need field values, so that doesn't affect us.\n //\n // Form ID resolution: live-verified against a real Forminator install\n // (2026-07-02) that the `response` argument Forminator hands to this\n // event is an EMPTY object ({}) \u2014 response.form_id does not exist in\n // practice, despite being documented elsewhere. The reliable source is\n // `event.target`, which jQuery sets to the <form> element itself (the\n // event bubbles from the form to document), carrying a `data-form-id`\n // attribute Forminator always renders.\n var successHooked = false;\n\n function hookForminatorSuccess() {\n if (successHooked) return true;\n if (typeof jQuery === 'undefined' && typeof $ === 'undefined') return false;\n\n var jQ = typeof jQuery !== 'undefined' ? jQuery : $;\n jQ(document).on('forminator:form:submit:success', function (event) {\n var formEl = event && event.target;\n var formId = (formEl && formEl.getAttribute && formEl.getAttribute('data-form-id')) || '';\n fireConversion(formId);\n });\n successHooked = true;\n return true;\n }\n\n // Retry hooking on DOMContentLoaded and window load \u2014 some sites load\n // jQuery/Forminator very late.\n if (!hookForminatorSuccess()) {\n document.addEventListener('DOMContentLoaded', function () {\n hookForminatorSuccess();\n });\n window.addEventListener('load', function () {\n hookForminatorSuccess();\n });\n }\n})();\n</script>"
+ "value": "<script>\n(function () {\n if (window.__ctForminatorForms) return;\n window.__ctForminatorForms = true;\n window.dataLayer = window.dataLayer || [];\n var listeners=[],lastEvent=null;\n window.__ctForminatorSubscribe=function(listener){if(listener&&typeof listener==='object')listeners.push(listener);};\n function isForm(form){\n try{return !!(form&&String(form.tagName||'').toLowerCase()==='form'&&form.classList&&form.classList.contains('forminator-custom-form'));}\n catch(e){return false;}\n }\n function notify(phase,form,candidate,event){\n var handled=false;\n for(var i=0;i<listeners.length;i++)try{var fn=listeners[i]&&listeners[i][phase];if(typeof fn==='function'&&fn(form,candidate,event)===true)handled=true;}catch(e){}\n return handled;\n }\n function submit(event){try{var form=event.target;if(isForm(form))notify('beforeAttempt',form,false,event);}catch(e){}}\n function success(event){\n try{\n if(event&&typeof event==='object'&&event===lastEvent)return;\n lastEvent=event;\n if(event&&typeof event==='object')setTimeout(function(){if(lastEvent===event)lastEvent=null;},0);\n var form=event&&event.target;if(!isForm(form))return;\n if(!notify('onCandidate',form,true,event))window.dataLayer.push({event:'forminator_form_submitted',form_id:form.getAttribute('data-form-id')||''});\n }catch(e){}\n }\n document.addEventListener('submit',submit,true);\n // Page-reload forms render their verdict in the returned page instead of\n // emitting the AJAX event. Read only the confirmation class and form ID.\n var confirmedForms=[];\n function nativeConfirmations(){\n try{\n var forms=document.querySelectorAll('form.forminator-custom-form:not(.forminator_ajax)');\n for(var i=0;i<forms.length;i++){\n var form=forms[i],message=form.querySelector('.forminator-response-message.forminator-success');\n if(!message||!message.getClientRects().length||confirmedForms.indexOf(form)!==-1)continue;\n confirmedForms.push(form);\n success({target:form});\n }\n }catch(e){}\n }\n function watchNative(){\n nativeConfirmations();\n if(window.MutationObserver&&document.documentElement){\n new MutationObserver(nativeConfirmations).observe(document.documentElement,{childList:true,subtree:true,attributes:true,attributeFilter:['class','style']});\n }\n }\n if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',watchNative);\n else watchNative();\n window.addEventListener('load',nativeConfirmations);\n function hook(){\n try{\n if(window.__ctForminatorSuccessHooked)return true;\n var jq=window.jQuery||(typeof jQuery!=='undefined'?jQuery:(typeof $!=='undefined'?$:null));\n if(!jq)return false;\n window.__ctForminatorSuccessHooked=true;\n jq(document).on('forminator:form:submit:success',success);return true;\n }catch(e){return false;}\n }\n if(!hook()){document.addEventListener('DOMContentLoaded',hook);window.addEventListener('load',hook);}\n})();\n</script>"
},
{
"type": "BOOLEAN",
diff --git a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-framer-forms.json b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-framer-forms.json
index 6f83636..09b78d3 100644
--- a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-framer-forms.json
+++ b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-framer-forms.json
@@ -29,7 +29,7 @@
{
"type": "TEMPLATE",
"key": "html",
- "value": "<script>\n(function () {\n // SUBMIT-BASED BEST EFFORT. Framer cancels the native submit and sends\n // the form by script, so a bubble-phase listener always sees it cancelled\n // and never fires. This listens in the capture phase, before Framer's own\n // handler runs, and fires on a submit that passes browser validation. It\n // is still submit-based, so a server-side rejection, a spam block or any\n // later custom validation still counts. A 2-second debounce per form only\n // collapses rapid repeats (a double click). Framer documents a\n // framer:formsubmit event, but it fires only when the form has a tracking\n // ID set and isn't documented as success-only, so this doesn't rely on\n // it. For exact counts, set the form to redirect to a thank-you page and\n // use thank-you-page.js instead.\n if (window.__ctDetectFramerForms) return;\n window.__ctDetectFramerForms = true;\n window.dataLayer = window.dataLayer || [];\n\n function fireConversion(formName) {\n window.dataLayer.push({\n event: 'framer_form_submitted',\n form_name: formName || ''\n });\n }\n\n function isFramerForm(formEl) {\n if (!formEl) return false;\n if (formEl.hasAttribute && formEl.hasAttribute('data-framer-name')) return true;\n var cls = typeof formEl.className === 'string' ? formEl.className : '';\n if (/(^|\\s)framer-[A-Za-z0-9_-]+/.test(cls)) return true;\n try {\n if (formEl.closest && formEl.closest('[data-framer-component-type]')) return true;\n if (formEl.closest && formEl.closest('[data-framer-name]')) return true;\n } catch (e) {\n // .closest not available — fall through\n }\n return false;\n }\n\n function handleSubmit(event) {\n try {\n var formEl = event.target;\n if (!formEl || (formEl.tagName || '').toLowerCase() !== 'form') return;\n if (!isFramerForm(formEl)) return;\n\n // Constraint validation gate: an invalid form cannot have submitted.\n try {\n if (typeof formEl.checkValidity === 'function' && formEl.checkValidity() === false) return;\n } catch (e) {\n // constraint validation unavailable — fall through\n }\n\n // Collapse rapid repeats on this same form element. Keyed on the\n // element itself, so two forms with the same name, or no name, don't\n // share a timestamp.\n var now = Date.now();\n if (formEl.__ctFramerLastFire && now - formEl.__ctFramerLastFire < 2000) return;\n formEl.__ctFramerLastFire = now;\n\n var formName = formEl.getAttribute('data-framer-name') || formEl.id || '';\n\n fireConversion(formName);\n } catch (e) {\n // Never throw back into Framer's own form handling.\n }\n }\n\n if (typeof document !== 'undefined' && document.addEventListener) {\n // Capture phase, so this runs before Framer's own handler cancels the\n // native submit.\n document.addEventListener('submit', handleSubmit, true);\n }\n})();\n</script>"
+ "value": "<script>\n(function () {\n if (window.__ctFramerForms) return;\n window.__ctFramerForms = true;\n window.dataLayer = window.dataLayer || [];\n var listeners = [];\n var pending = [];\n window.__ctFramerSubscribe = function (listener) {\n if (listener && typeof listener === 'object') listeners.push(listener);\n };\n function isFramerForm(form) {\n try {\n if (!form || String(form.tagName || '').toLowerCase() !== 'form') return false;\n if (form.hasAttribute && form.hasAttribute('data-framer-name')) return true;\n if (typeof form.className === 'string' && /(^|\\s)framer-[A-Za-z0-9_-]+/.test(form.className)) return true;\n return !!(form.closest && (form.closest('[data-framer-component-type]') || form.closest('[data-framer-name]')));\n } catch (e) { return false; }\n }\n function notify(phase, form, candidate) {\n var handled = false;\n for (var i = 0; i < listeners.length; i++) {\n try {\n var fn = listeners[i] && listeners[i][phase];\n if (typeof fn === 'function' && fn(form, candidate) === true) handled = true;\n } catch (e) {}\n }\n return handled;\n }\n function remember(form) {\n try {\n if (!isFramerForm(form)) return;\n for (var i = 0; i < pending.length; i++) {\n if (pending[i].form === form) return;\n }\n pending.push({ form: form, time: Date.now(), claimed: false });\n notify('beforeAttempt', form, false);\n } catch (e) {}\n }\n function finish(attempts, accepted) {\n for (var i = 0; i < attempts.length; i++) {\n var index = pending.indexOf(attempts[i]);\n if (index !== -1) pending.splice(index, 1);\n }\n if (!accepted) return;\n // Concurrent forms cannot be attributed without inspecting answers.\n // Keep those submissions event-only, with no guessed form name.\n var form = attempts.length === 1 ? attempts[0].form : null;\n var name = form ? form.getAttribute('data-framer-name') || form.id || '' : '';\n if (!form || !notify('onCandidate', form, true)) {\n window.dataLayer.push({ event: 'framer_form_submitted', form_name: name });\n }\n }\n if (typeof window.fetch === 'function') {\n var originalFetch = window.fetch;\n window.fetch = function (input, options) {\n var attempts = null;\n try {\n var url = typeof input === 'string' ? input : input && input.url;\n var method = options && options.method || input && input.method || 'GET';\n if (String(method).toUpperCase() === 'POST' && /^https:\\/\\/api\\.framer\\.com\\/forms\\/v1\\/forms\\/[a-f0-9-]+\\/submit(?:\\?.*)?$/.test(url || '')) {\n attempts = [];\n var now = Date.now();\n pending = pending.filter(function (attempt) { return now - attempt.time < 60000; });\n for (var i = 0; i < pending.length; i++) {\n if (!pending[i].claimed) {\n pending[i].claimed = true;\n attempts.push(pending[i]);\n }\n }\n }\n } catch (e) {}\n var result = originalFetch.apply(this, arguments);\n if (attempts) result.then(function (response) {\n try { finish(attempts, response.ok === true); } catch (e) {}\n }, function () {\n try { finish(attempts, false); } catch (e) {}\n });\n return result;\n };\n }\n if (typeof document !== 'undefined' && document.addEventListener) {\n document.addEventListener('submit', function (event) { remember(event.target); }, true);\n // Framer handles Enter directly instead of dispatching native submit.\n document.addEventListener('keydown', function (event) {\n var target = event.target;\n if (event.key === 'Enter' && target && String(target.tagName).toLowerCase() !== 'textarea') {\n var form = target.form;\n if (isFramerForm(form) && form.matches(':valid')) remember(form);\n }\n }, true);\n }\n})();\n</script>"
},
{
"type": "BOOLEAN",
@@ -100,4 +100,4 @@
"fingerprint": "0",
"tagManagerUrl": "https://tagmanager.google.com/#/container/accounts/0/containers/0/workspaces/0"
}
-}
+}
\ No newline at end of file
diff --git a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-gravity-forms.json b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-gravity-forms.json
index c2ee45c..65ca731 100644
--- a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-gravity-forms.json
+++ b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-gravity-forms.json
@@ -29,7 +29,7 @@
{
"type": "TEMPLATE",
"key": "html",
- "value": "<script>\n(function () {\n if (window.__ctDetectGravityForms) return;\n window.__ctDetectGravityForms = true;\n window.dataLayer = window.dataLayer || [];\n\n // Dedup between the two fire paths. On a normal setup BOTH paths see the\n // same submission (the jQuery event fires first, the MutationObserver a few\n // milliseconds later \u2014 live-verified), and the two report the form id with\n // different types (number vs string), so we dedup on time, not on id: any\n // fire within 3s of the last one is the same submission. A genuine second\n // submission can't complete inside 3s (it needs a refill plus a server\n // round trip).\n var lastFiredAt = 0;\n var DEDUP_WINDOW_MS = 3000;\n\n function fireConversion(formId) {\n var now = Date.now();\n if (now - lastFiredAt < DEDUP_WINDOW_MS) return;\n lastFiredAt = now;\n window.dataLayer.push({\n event: 'gravity_form_submitted',\n form_id: String(formId || '')\n });\n }\n\n // Fire path 1 \u2014 GF's own jQuery event, fired on `document` after an AJAX\n // submission's confirmation renders. Covers every GF version that ships\n // jQuery on window.\n function hookConfirmationEvent() {\n if (typeof window.jQuery === 'undefined') return false;\n window.jQuery(document).on('gform_confirmation_loaded', function (event, formId) {\n fireConversion(formId);\n });\n return true;\n }\n\n // Fire path 2 \u2014 MutationObserver fallback for setups where window.jQuery\n // isn't reachable. GF replaces the form wrapper with a\n // .gform_confirmation_message element on AJAX success; the form id is\n // encoded in its id attribute (gform_confirmation_message_5).\n function checkNode(node) {\n if (!node || node.nodeType !== 1) return;\n var conf = null;\n if (node.classList && node.classList.contains('gform_confirmation_message')) {\n conf = node;\n } else if (node.querySelector) {\n conf = node.querySelector('.gform_confirmation_message, [id^=\"gform_confirmation_message_\"]');\n }\n if (!conf) return;\n var m = /gform_confirmation_message_(\\d+)/.exec(conf.id || '');\n fireConversion(m ? m[1] : '');\n }\n\n function observeConfirmations() {\n if (typeof MutationObserver === 'undefined') return;\n var observer = new MutationObserver(function (muts) {\n for (var i = 0; i < muts.length; i++) {\n var added = muts[i].addedNodes;\n if (!added) continue;\n for (var j = 0; j < added.length; j++) checkNode(added[j]);\n }\n });\n observer.observe(document.body || document.documentElement, {\n childList: true,\n subtree: true\n });\n }\n\n if (!hookConfirmationEvent()) {\n window.addEventListener('load', hookConfirmationEvent);\n }\n observeConfirmations();\n})();\n</script>"
+ "value": "<script>\n/* Gravity Forms Submission Listener.\n * Event-only adaptation of verified production detection helpers.\n * Source SHA256 3ed591d48dc449e94fd48f634bb07ae8285f5d661a4b48fc5db867ca3e659b69.\n * Reads no form field values. Sends only event and form_id to dataLayer.\n * Native handoff stores only form ID, source path and time in sessionStorage.\n */\n(function(){\n\"use strict\";\nif(window.__ctGalleryGravityForms)return;\nwindow.__ctGalleryGravityForms=true;\n// Preserve the original recipe guard for an old recipe loaded after this code.\n// Do not return on the legacy guard: an old-first listener is independently\n// active and remains an unsupported migration state, but must not suppress us.\nwindow.__ctDetectGravityForms=true;\nfunction isGravityForm(formEl) {\n if (!formEl) return false;\n // Check for gform_wrapper parent or gform_ ID prefix\n try {\n if (formEl.closest && formEl.closest('.gform_wrapper')) return true;\n } catch (e) {\n // .closest not available — fall back to ID check\n }\n // Fallback: GF forms have IDs like \"gform_1\", \"gform_5\"\n var id = formEl.id || '';\n return /^gform_\\d+$/.test(id);\n }\n\nfunction getFormId(formEl) {\n if (!formEl) return null;\n var fid = (formEl.getAttribute && formEl.getAttribute('data-formid')) || '';\n if (fid) return String(fid);\n var id = formEl.id || '';\n var m = /gform_(\\d+)/.exec(id);\n return m ? m[1] : null;\n }\n\nfunction isAjaxForm(formEl) {\n if (!formEl) return false;\n try {\n var target = (formEl.getAttribute && formEl.getAttribute('target')) || '';\n if (target.indexOf('gform_ajax_frame_') === 0) return true;\n if (formEl.querySelector && formEl.querySelector('input[name=\"gform_ajax\"]')) {\n return true;\n }\n } catch (e) {\n // DOM access failed — treat as non-AJAX; the reload path is the\n // safer default (it still only fires on confirmed success).\n }\n return false;\n }\n\nfunction isNodeHidden(el) {\n try {\n if (el.hidden) return true;\n if (el.getAttribute && el.getAttribute('aria-hidden') === 'true') return true;\n var view = el.ownerDocument && el.ownerDocument.defaultView;\n if (view && view.getComputedStyle) {\n var cs = view.getComputedStyle(el);\n if (cs && (cs.display === 'none' || cs.visibility === 'hidden')) return true;\n }\n } catch (e) {\n // fall through\n }\n return false;\n }\n\nfunction hasVisibleValidationErrors(rootEl) {\n if (!rootEl || !rootEl.querySelectorAll) return false;\n try {\n if (rootEl.className &&\n (' ' + rootEl.className + ' ').indexOf(' gform_validation_error ') !== -1) {\n return true;\n }\n var nodes = rootEl.querySelectorAll(\n '.gform_validation_errors, .validation_error, .gfield_error, .validation_message, [aria-invalid=\"true\"]'\n );\n for (var i = 0; i < nodes.length; i++) {\n var node = nodes[i];\n if (isNodeHidden(node)) continue;\n if (node.getAttribute && node.getAttribute('aria-invalid') === 'true') return true;\n // Error classes and ARIA state are structural signals. Never read\n // rendered validation text: themes may include resolved field values.\n var classes = typeof node.className === 'string' ? node.className : '';\n if (/^(?:.*\\s)?(?:gform_validation_errors|validation_error|gfield_error)(?:\\s.*)?$/.test(classes)) return true;\n }\n } catch (e) {\n // fall through\n }\n return false;\n }\n\nfunction safeFormId(formId) {\n if (formId == null) return null;\n var s = String(formId);\n return /^\\d+$/.test(s) ? s : null;\n }\n\nfunction hasServerRejectionMarkers(formId) {\n var fid = safeFormId(formId);\n try {\n if (fid) {\n var scope = document.querySelector('#gform_wrapper_' + fid) ||\n document.querySelector('#gform_' + fid + ', form[data-formid=\"' + fid + '\"]');\n if (scope && scope.closest) {\n scope = scope.closest('.gform_wrapper') || scope;\n }\n // The submitted form isn't on this page at all → no rejection\n // evidence FOR THIS FORM, whatever other forms are showing.\n return scope ? hasVisibleValidationErrors(scope) : false;\n }\n var wrappers = document.querySelectorAll('.gform_wrapper');\n for (var i = 0; i < wrappers.length; i++) {\n if (hasVisibleValidationErrors(wrappers[i])) return true;\n }\n } catch (e) {\n // fall through\n }\n return false;\n }\n\nfunction hasConfirmationMessage(formId) {\n var fid = safeFormId(formId);\n try {\n var nodes = document.querySelectorAll(\n '.gform_confirmation_message, [id^=\"gform_confirmation_message_\"], [id^=\"gform_confirmation_wrapper_\"]'\n );\n for (var i = 0; i < nodes.length; i++) {\n var node = nodes[i];\n if (isNodeHidden(node)) continue;\n // Presence of a visible, form-attributed confirmation element is a\n // structural legacy signal; its rendered contents are never inspected.\n if (!fid) continue;\n // Attribute the node to a form id if it carries one (own id or an\n // ancestor confirmation-wrapper id).\n var taggedId = null;\n var m = /gform_confirmation_(?:message|wrapper)_(\\d+)/.exec(node.id || '');\n if (m) {\n taggedId = m[1];\n } else if (node.closest) {\n try {\n var anc = node.closest('[id^=\"gform_confirmation_wrapper_\"], [id^=\"gform_confirmation_message_\"]');\n var am = anc && /_(\\d+)$/.exec(anc.id || '');\n if (am) taggedId = am[1];\n } catch (e2) {\n // .closest unavailable — treat as untagged\n }\n }\n if (taggedId === fid) return true;\n }\n } catch (e) {\n // fall through\n }\n return false;\n }\nvar pending={},complete={},TTL=120000,markerKey='__ct_gallery_gf_pending_v3';\nvar modernHookInstalled=false,seenEntries={};\nwindow.dataLayer=window.dataLayer||[];\nfunction forget(id){var entry=pending[id];if(entry&&entry.timer)clearTimeout(entry.timer);delete pending[id];}\nfunction discardNotice(id,reason,form){try{document.dispatchEvent(new CustomEvent('ct:gform-attempt-discarded',{detail:{formId:String(id||''),reason:reason||'discarded',form:form||null}}));}catch(e){}}\nfunction emitConfirmed(id,form,uniqueAccepted){id=safeFormId(id);if(!id||(!uniqueAccepted&&complete[id]))return;complete[id]=true;var handled=false;try{if(typeof window.__ctGravityMethod2Emit==='function')handled=window.__ctGravityMethod2Emit(id,form)===true;}catch(e){}if(!handled)window.dataLayer.push({event:'gravity_form_submitted',form_id:id});}\nfunction fireLegacy(id){id=safeFormId(id);if(modernHookInstalled||!id||!pending[id]||complete[id])return;var form=pending[id].form;forget(id);emitConfirmed(id,form);}\nfunction attempt(form,method,type){\n if(!isGravityForm(form))return;var id=safeFormId(getFormId(form));if(!id)return;\n if(modernHookInstalled){return;}\n if(type&&type!=='submit'){forget(id);discardNotice(id,'nonfinal');return;}\n forget(id);complete[id]=false;\n var entry={form:form,method:method||(isAjaxForm(form)?'iframe':'postback'),trusted:method==='postback',time:Date.now(),path:location.pathname,timer:null};\n entry.timer=setTimeout(function(){if(pending[id]===entry){forget(id);discardNotice(id,'timeout');}},TTL);pending[id]=entry;\n}\nfunction acceptedIframe(frame){\n if(modernHookInstalled||!frame||frame.tagName!=='IFRAME'||!/^gform_ajax_frame_\\d+$/.test(frame.id||''))return;\n var id=frame.id.replace('gform_ajax_frame_','');if(!pending[id])return;\n try{var doc=frame.contentDocument;if(!doc||!doc.querySelector('.GF_AJAX_POSTBACK'))return;if(doc.querySelector('.gform_validation_error, .gform_validation_errors, .gfield_error, [aria-invalid=\\\"true\\\"]')){forget(id);discardNotice(id,'rejected');return;}var confirmation=doc.querySelector('#gform_confirmation_wrapper_'+id+', #gform_confirmation_message_'+id);if(confirmation&&!isNodeHidden(confirmation))fireLegacy(id);}catch(e){}\n}\ndocument.addEventListener('load',function(event){acceptedIframe(event.target);},true);\nvar jqueryHooked=false;\nfunction hook(){\n if(!jqueryHooked&&typeof window.jQuery==='function'){jqueryHooked=true;window.jQuery(document).on('gform_confirmation_loaded.ctGallery',function(event,id){fireLegacy(id);});}\n if(modernHookInstalled||!window.gform||!gform.utils||!gform.utils.addAsyncFilter)return;\n modernHookInstalled=true;\n gform.utils.addAsyncFilter('gform/submission/pre_submission',function(data){\n var form=data&&data.form;if(form&&!form.tagName&&form[0])form=form[0];var id=safeFormId(getFormId(form));\n if(!id)return data;\n if(data.submissionType!=='submit'){\n discardNotice(id,'nonfinal',form);\n return data;\n }\n if(data.abort===true)return data;\n if(data.submissionMethod==='postback'||data.submissionMethod==='iframe')data.submissionMethod='ajax';\n return data;\n });\n gform.utils.addAsyncFilter('gform/submission/submission_started',function(data){\n var form=data&&data.form;if(form&&!form.tagName&&form[0])form=form[0];var id=safeFormId(getFormId(form));\n if(id&&data.submissionType==='submit')complete[id]=false;\n return data;\n });\n gform.utils.addAsyncFilter('gform/ajax/post_ajax_submission',function(data){\n var form=data&&data.form;if(form&&!form.tagName&&form[0])form=form[0];var id=safeFormId(getFormId(form));if(!id)return data;\n var result=data&&data.submissionResult,verdict=result&&result.data;\n var rawEntryId=verdict&&verdict.entry_id,entryId=typeof rawEntryId==='number'?rawEntryId:(typeof rawEntryId==='string'&&/^\\d+$/.test(rawEntryId)?Number(rawEntryId):NaN);\n var key=id+':'+entryId;\n if(result&&result.success===true&&verdict&&verdict.is_valid===true&&verdict.submission_type==='submit'&&isFinite(entryId)&&Math.floor(entryId)===entryId&&entryId>0&&entryId<=9007199254740991&&verdict.is_spam===false){\n if(seenEntries[key]){discardNotice(id,'duplicate-entry',form);return data;}\n seenEntries[key]=true;emitConfirmed(id,form,true);\n }else if(result&&result.success===true)discardNotice(id,'rejected',form);\n return data;\n });\n gform.utils.addAsyncFilter('gform/ajax/pre_display_error',function(data){\n if(data&&data.formId){var errorForm=null;try{errorForm=document.querySelector('#gform_'+safeFormId(data.formId));}catch(e){}discardNotice(data.formId,'ajax-error',errorForm);}\n return data;\n });\n document.addEventListener('gform/submission/submission_aborted',function(event){\n var form=event&&event.detail&&event.detail.form,id=safeFormId(getFormId(form));\n if(id)discardNotice(id,'abort',form);\n });\n}\nhook();document.addEventListener('gform/theme/scripts_loaded',hook);document.addEventListener('DOMContentLoaded',hook);window.addEventListener('load',hook);\ndocument.addEventListener('submit',function(event){attempt(event.target,null,'submit');},true);\ndocument.addEventListener('click',function(event){var el=event.target;if(!el||!el.closest)return;var control=el.closest('[id^=\"gform_submit_button_\"]');if(control)attempt(control.closest('form'),null,'submit');},true);\nfunction confirmationNode(node){if(modernHookInstalled||!node||node.nodeType!==1)return;var nodes=[];if(node.matches&&node.matches('[id^=\"gform_confirmation_message_\"], [id^=\"gform_confirmation_wrapper_\"]'))nodes.push(node);if(node.querySelectorAll){var list=node.querySelectorAll('[id^=\"gform_confirmation_message_\"], [id^=\"gform_confirmation_wrapper_\"]');for(var i=0;i<list.length;i++)nodes.push(list[i]);}for(var j=0;j<nodes.length;j++){var match=/gform_confirmation_(?:message|wrapper)_(\\d+)/.exec(nodes[j].id||'');if(match&&!isNodeHidden(nodes[j]))fireLegacy(match[1]);}}\nif(typeof MutationObserver==='function')new MutationObserver(function(mutations){for(var i=0;i<mutations.length;i++)for(var j=0;j<mutations[i].addedNodes.length;j++)confirmationNode(mutations[i].addedNodes[j]);}).observe(document.body||document.documentElement,{childList:true,subtree:true});\nwindow.addEventListener('pagehide',function(){\n var markers=[];for(var id2 in pending)if(Object.prototype.hasOwnProperty.call(pending,id2)){var entry=pending[id2];if(entry.method!=='postback'||Date.now()-entry.time>10000||(!entry.trusted&&hasVisibleValidationErrors(entry.form)))continue;markers.push({id:id2,time:entry.time,path:entry.path});}\n if(markers.length)try{sessionStorage.setItem(markerKey,JSON.stringify(markers));}catch(e){}\n});\nfunction deferred(){if(modernHookInstalled)return;var markers;try{var raw=sessionStorage.getItem(markerKey);sessionStorage.removeItem(markerKey);markers=JSON.parse(raw||'[]');}catch(e){return;}if(!Array.isArray(markers))return;for(var i=0;i<markers.length;i++){var marker=markers[i],id=safeFormId(marker&&marker.id);if(!id||!marker.time||Date.now()-marker.time>60000)continue;if(hasServerRejectionMarkers(id))continue;if(hasConfirmationMessage(id)){pending[id]={};fireLegacy(id);}}}\nif(document.readyState==='loading')document.addEventListener('DOMContentLoaded',deferred);else deferred();\n\n})();\n</script>"
},
{
"type": "BOOLEAN",
diff --git a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-jotform.json b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-jotform.json
index aa2d277..f61b1b9 100644
--- a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-jotform.json
+++ b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-jotform.json
@@ -29,7 +29,7 @@
{
"type": "TEMPLATE",
"key": "html",
- "value": "<script>\n(function () {\n if (window.__ctDetectJotform) return;\n window.__ctDetectJotform = true;\n window.dataLayer = window.dataLayer || [];\n\n // Two embed styles, two signals of different strength:\n //\n // 1. IFRAME embed (the default Jotform embed code). Jotform doesn't\n // document any submission message from its embed. In testing a classic\n // form, nothing reached the host page after submit, and Jotform's own\n // embed script handles that message only for Card-layout forms. A form\n // showing an on-page thank-you message wasn't tested. So for iframe\n // embeds, set the form's thank-you to redirect to a page on this site\n // and use thank-you-page.js there. Use one method or the other for a\n // given form, never both. The message listener below is kept only as a\n // fallback. It fires only for a message from a Jotform iframe on this\n // page that shows the same form ID, and at most once per form.\n //\n // 2. SOURCE-CODE embed (the form's raw HTML pasted into the page, a\n // <form class=\"jotform-form\"> posting to submit.jotform.com). Jotform\n // validates in its own handler, cancels every native submit and then\n // submits the form itself, so a listener that skips cancelled submits\n // never fires. This path marks the form on submit (capture phase) and\n // fires when the browser builds the form's data for the real send (the\n // formdata event), once per form. In the tested flow (a classic form\n // with Jotform's own validation on), a submit Jotform rejects builds no\n // data and doesn't count. A server-side rejection or spam block after\n // the send still counts.\n // Known limits. If another script builds the form's data after a\n // rejected attempt, that counts. Payment, multi-page, save-and-continue\n // and captcha forms haven't been tested, so prefer the thank-you\n // redirect plus thank-you-page.js there.\n\n var JOTFORM_FORM_ID_RE = /^\\d{10,}$/;\n var JOTFORM_SUBMIT_ACTION_RE = /^https?:\\/\\/submit\\.jotform\\.com\\//i;\n var JOTFORM_ORIGIN_RE = /(^|\\.)jotform(eu)?\\.com$/;\n\n // Form IDs already counted on this page, shared by both paths.\n var fired = {};\n\n function fireConversion(formId) {\n window.dataLayer.push({\n event: 'jotform_form_submitted',\n form_id: formId || ''\n });\n }\n\n // ---- Path 1: iframe embed, message listener kept as a fallback ----\n\n // True when the iframe's src is a Jotform form host and one of its path\n // segments is exactly this form ID.\n function frameShowsForm(frame, formId) {\n var src = (frame.getAttribute && frame.getAttribute('src')) || '';\n if (!src) return false;\n var url;\n try {\n url = new URL(src, window.location.href);\n } catch (e) {\n return false;\n }\n if (!JOTFORM_ORIGIN_RE.test(url.hostname.toLowerCase())) return false;\n var parts = url.pathname.split('/');\n for (var i = 0; i < parts.length; i++) {\n if (parts[i] === formId) return true;\n }\n return false;\n }\n\n // Frames are looked up when the message arrives, so an iframe inserted\n // after this snippet loaded still binds.\n function sourceIsFormFrame(source, formId) {\n var frames = document.getElementsByTagName('iframe');\n for (var i = 0; i < frames.length; i++) {\n var win = null;\n try { win = frames[i].contentWindow; } catch (e) { win = null; }\n if (win && win === source && frameShowsForm(frames[i], formId)) return true;\n }\n return false;\n }\n\n function handleMessage(event) {\n try {\n if (!event || !event.source || event.source === window) return;\n if (!event.origin || typeof event.origin !== 'string') return;\n var hostMatch = /^https:\\/\\/([^/]+)$/.exec(event.origin);\n if (!hostMatch || !JOTFORM_ORIGIN_RE.test(hostMatch[1])) return;\n\n var data = event.data;\n if (typeof data === 'string') {\n if (data.indexOf('submission-completed') === -1) return;\n try { data = JSON.parse(data); } catch (e) { return; }\n }\n if (!data || typeof data !== 'object') return;\n if (data.action !== 'submission-completed') return;\n\n var formId = String(data.formID || data.formId || '');\n if (!JOTFORM_FORM_ID_RE.test(formId)) return;\n if (fired[formId]) return;\n if (!sourceIsFormFrame(event.source, formId)) return;\n\n fireConversion(formId);\n fired[formId] = true;\n } catch (e) {\n // Never throw back into the page's own message handling.\n }\n }\n\n window.addEventListener('message', handleMessage, false);\n\n // ---- Path 2: source-code embed, submission built ----\n\n function isJotformInlineForm(formEl) {\n if (!formEl || (formEl.tagName || '').toLowerCase() !== 'form') return false;\n var hasClass = formEl.classList && formEl.classList.contains('jotform-form');\n var action = formEl.getAttribute && formEl.getAttribute('action');\n var hasAction = action && JOTFORM_SUBMIT_ACTION_RE.test(action);\n if (!hasClass && !hasAction) return false;\n var id = formEl.id || '';\n if (!JOTFORM_FORM_ID_RE.test(id)) return false;\n return true;\n }\n\n var attempted = {};\n\n // Capture phase, so this sees the submit before Jotform cancels it.\n document.addEventListener('submit', function (event) {\n var formEl = event.target;\n if (!isJotformInlineForm(formEl)) return;\n attempted[formEl.id] = true;\n }, true);\n\n // Chromium can raise formdata twice for one submission, so the fired\n // check is what keeps this to one conversion per form. The form is marked\n // fired only after the push succeeds.\n document.addEventListener('formdata', function (event) {\n try {\n var formEl = event.target;\n if (!isJotformInlineForm(formEl)) return;\n if (!attempted[formEl.id] || fired[formEl.id]) return;\n fireConversion(formEl.id);\n fired[formEl.id] = true;\n } catch (e) {\n // Never throw back into Jotform's own submit handling.\n }\n }, true);\n})();\n</script>"
+ "value": "<script>\n/* Jotform iframe completion listener. Reads no form answers.\n * Counts once per embedded frame on this page. */\n(function () {\n 'use strict';\n if (window.__ctDetectJotform || window.__ctJotformMethod2Installed) return;\n window.__ctDetectJotform = true;\n window.__ctJotformMethod2Installed = true;\n var completed = [];\n window.addEventListener('message', function (event) {\n if (!event.source || event.source === window) return;\n if (!/^https:\\/\\/(form|submit)\\.jotform\\.com$/.test(event.origin)) return;\n var data = event.data;\n if (!data || typeof data !== 'object' || Array.isArray(data) || data.action !== 'submission-completed') return;\n var frames = document.querySelectorAll('iframe');\n for (var i = 0; i < frames.length; i++) {\n var frame = frames[i];\n if (frame.contentWindow !== event.source) continue;\n var match = /^https:\\/\\/form\\.jotform\\.com\\/(\\d+)(?:[/?#]|$)/.exec(frame.getAttribute('src') || '');\n if (!match || (data.formID != null && String(data.formID) !== match[1])) return;\n if (completed.indexOf(frame) !== -1) return;\n completed.push(frame);\n window.dataLayer = window.dataLayer || [];\n window.dataLayer.push({ event: 'jotform_form_submitted', form_id: match[1] });\n return;\n }\n });\n})();\n</script>"
},
{
"type": "BOOLEAN",
@@ -100,4 +100,4 @@
"fingerprint": "0",
"tagManagerUrl": "https://tagmanager.google.com/#/container/accounts/0/containers/0/workspaces/0"
}
-}
+}
\ No newline at end of file
diff --git a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-ninja-forms.json b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-ninja-forms.json
index 24ef894..c3d5d5d 100644
--- a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-ninja-forms.json
+++ b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-ninja-forms.json
@@ -29,7 +29,7 @@
{
"type": "TEMPLATE",
"key": "html",
- "value": "<script>\n(function () {\n if (window.__ctDetectNinjaForms) return;\n window.__ctDetectNinjaForms = true;\n window.dataLayer = window.dataLayer || [];\n\n function fireConversion(formId) {\n window.dataLayer.push({\n event: 'ninja_forms_submitted',\n form_id: formId || ''\n });\n }\n\n function responseHasErrors(response) {\n if (!response || !response.errors) return false;\n var errors = response.errors;\n if (typeof errors.length === 'number') return errors.length > 0;\n if (typeof errors !== 'object') return !!errors;\n for (var key in errors) {\n if (!Object.prototype.hasOwnProperty.call(errors, key)) continue;\n var group = errors[key];\n if (!group) continue;\n if (typeof group.length === 'number') {\n if (group.length > 0) return true;\n } else if (typeof group === 'object') {\n for (var sub in group) {\n if (Object.prototype.hasOwnProperty.call(group, sub)) return true;\n }\n } else {\n return true;\n }\n }\n return false;\n }\n\n function handleSubmitResponse(response) {\n if (responseHasErrors(response)) return;\n var formId = (response && response.data && response.data.form_id) ? response.data.form_id : '';\n fireConversion(formId);\n }\n\n var radioHooked = false;\n\n function hookNfRadio() {\n if (radioHooked) return true;\n\n if (typeof nfRadio !== 'undefined' && nfRadio.channel) {\n try {\n nfRadio.channel('forms').on('submit:response', handleSubmitResponse);\n radioHooked = true;\n return true;\n } catch (e) {\n }\n }\n\n if (typeof Backbone !== 'undefined' && Backbone.Radio) {\n try {\n Backbone.Radio.channel('forms').on('submit:response', handleSubmitResponse);\n radioHooked = true;\n return true;\n } catch (e) {\n }\n }\n\n return false;\n }\n\n var observerStarted = false;\n\n function startMutationObserver() {\n if (observerStarted) return;\n if (typeof MutationObserver === 'undefined') return;\n\n var containers = document.querySelectorAll('.nf-form-cont');\n if (containers.length === 0) return;\n\n observerStarted = true;\n\n for (var c = 0; c < containers.length; c++) {\n (function (container) {\n var observer = new MutationObserver(function (mutations) {\n for (var m = 0; m < mutations.length; m++) {\n var addedNodes = mutations[m].addedNodes;\n for (var n = 0; n < addedNodes.length; n++) {\n var node = addedNodes[n];\n if (!node || node.nodeType !== 1) continue;\n\n var isResponseMsg = false;\n if (node.classList && node.classList.contains('nf-response-msg')) {\n isResponseMsg = true;\n } else if (node.querySelector) {\n isResponseMsg = !!node.querySelector('.nf-response-msg');\n }\n\n if (isResponseMsg) fireConversion('');\n }\n }\n });\n\n observer.observe(container, { childList: true, subtree: true });\n })(containers[c]);\n }\n }\n\n var hooked = hookNfRadio();\n if (!hooked) {\n document.addEventListener('DOMContentLoaded', function () {\n var retryHooked = hookNfRadio();\n if (!retryHooked) startMutationObserver();\n });\n window.addEventListener('load', function () {\n if (!radioHooked) hookNfRadio();\n if (!observerStarted && !radioHooked) startMutationObserver();\n });\n }\n})();\n</script>"
+ "value": "<script>\n(function () {\n 'use strict';\n var runtime = window.__ctNinjaFormsRuntime;\n if (runtime && runtime.installed) return;\n\n // Preserve the recipe's public duplicate-install guard. If a superseded\n // snippet already set it without this runtime, fail closed: don't layer a\n // second listener over an unknown old detector.\n if (!runtime && window.__ctDetectNinjaForms) return;\n\n if (!runtime) {\n runtime = { seenEntryIds: Object.create(null), installed: false };\n window.__ctNinjaFormsRuntime = runtime;\n }\n window.__ctDetectNinjaForms = true;\n window.dataLayer = window.dataLayer || [];\n\n var MISSING = {};\n var MAX_SAFE_INTEGER = 9007199254740991;\n\n // Read only own data properties. Callback payloads are normally parsed JSON,\n // but a filter or another page script can supply accessor-backed objects.\n // Do not execute getters while deciding whether a response proves a save.\n function ownDataValue(object, key) {\n if (!object || typeof object !== 'object' || !Object.prototype.hasOwnProperty.call(object, key)) return MISSING;\n if (typeof Object.getOwnPropertyDescriptor !== 'function') return MISSING;\n var descriptor = Object.getOwnPropertyDescriptor(object, key);\n if (!descriptor || !Object.prototype.hasOwnProperty.call(descriptor, 'value')) return MISSING;\n return descriptor.value;\n }\n\n function emptyErrors(value) {\n if (Object.prototype.toString.call(value) === '[object Array]') return value.length === 0;\n if (!value || typeof value !== 'object') return false;\n for (var key in value) {\n if (Object.prototype.hasOwnProperty.call(value, key)) return false;\n }\n return true;\n }\n\n // Accept only primitive safe integers or canonical decimal strings. Never\n // coerce booleans, arrays, objects, boxed numbers, or accessor-backed IDs.\n function positiveIntegerId(value) {\n if (typeof value === 'number') {\n if (!isFinite(value) || value <= 0 || Math.floor(value) !== value || value > MAX_SAFE_INTEGER) return null;\n return String(value);\n }\n if (typeof value !== 'string' || !/^[1-9]\\d*$/.test(value)) return null;\n var number = Number(value);\n if (!isFinite(number) || number > MAX_SAFE_INTEGER || String(number) !== value) return null;\n return value;\n }\n\n function canonicalFormId(value) {\n var formId;\n if (typeof value === 'number') {\n if (!isFinite(value) || value <= 0 || Math.floor(value) !== value || value > MAX_SAFE_INTEGER) return null;\n formId = String(value);\n } else if (typeof value === 'string') {\n formId = value;\n } else {\n return null;\n }\n if (!/^[1-9]\\d*(?:_(?:0|[1-9]\\d*))*$/.test(formId)) return null;\n var parts = formId.split('_');\n for (var i = 0; i < parts.length; i++) {\n var part = Number(parts[i]);\n if (!isFinite(part) || part > MAX_SAFE_INTEGER || String(part) !== parts[i]) return null;\n }\n return formId;\n }\n\n function inspectResponse(response, callbackFormId) {\n var errors = ownDataValue(response, 'errors');\n if (errors === MISSING || !emptyErrors(errors)) return null;\n var data = ownDataValue(response, 'data');\n if (!data || typeof data !== 'object') return null;\n var halt = ownDataValue(data, 'halt');\n if (halt !== MISSING && halt) return null;\n var nestedErrors = ownDataValue(data, 'errors');\n if (nestedErrors !== MISSING && !emptyErrors(nestedErrors)) return null;\n var formValue = ownDataValue(data, 'form_id');\n var formId = formValue === MISSING ? null : canonicalFormId(formValue);\n if (!formId || canonicalFormId(callbackFormId) !== formId) return null;\n var actions = ownDataValue(data, 'actions');\n if (!actions || typeof actions !== 'object') return null;\n var save = ownDataValue(actions, 'save');\n if (!save || typeof save !== 'object') return null;\n var saveValue = ownDataValue(save, 'sub_id');\n var entryId = saveValue === MISSING ? null : positiveIntegerId(saveValue);\n if (!entryId) return null;\n return { formId: formId, entryId: entryId };\n }\n\n runtime.inspectResponse = inspectResponse;\n\n function handleSubmitResponse(response, textStatus, jqXHR, callbackFormId) {\n var accepted = inspectResponse(response, callbackFormId);\n if (!accepted) {\n if (typeof window.__ctNinjaMethod2AfterResponse === 'function') {\n window.__ctNinjaMethod2AfterResponse(callbackFormId, false, false);\n }\n return;\n }\n\n var key = '$' + accepted.entryId;\n if (runtime.seenEntryIds[key]) {\n if (typeof window.__ctNinjaMethod2AfterResponse === 'function') {\n window.__ctNinjaMethod2AfterResponse(accepted.formId, false, true);\n }\n return;\n }\n runtime.seenEntryIds[key] = true;\n\n var enriched = false;\n if (typeof window.__ctNinjaMethod2Emit === 'function') {\n try {\n enriched = window.__ctNinjaMethod2Emit(accepted.formId, accepted.entryId) === true;\n } catch (e) {\n enriched = false;\n }\n }\n if (!enriched) {\n window.dataLayer.push({ event: 'ninja_forms_submitted', form_id: accepted.formId });\n }\n if (typeof window.__ctNinjaMethod2AfterResponse === 'function') {\n window.__ctNinjaMethod2AfterResponse(accepted.formId, true, false);\n }\n }\n\n function hookNfRadio() {\n if (runtime.installed) return true;\n var radio = typeof nfRadio !== 'undefined' && nfRadio.channel ? nfRadio :\n (typeof Backbone !== 'undefined' && Backbone.Radio ? Backbone.Radio : null);\n if (!radio) return false;\n try {\n radio.channel('forms').on('submit:response', handleSubmitResponse);\n runtime.installed = true;\n return true;\n } catch (e) {\n return false;\n }\n }\n\n if (!hookNfRadio()) {\n document.addEventListener('DOMContentLoaded', hookNfRadio);\n window.addEventListener('load', hookNfRadio);\n }\n})();\n</script>"
},
{
"type": "BOOLEAN",
diff --git a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-tally.json b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-tally.json
index 120a533..47e40fa 100644
--- a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-tally.json
+++ b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-tally.json
@@ -29,7 +29,7 @@
{
"type": "TEMPLATE",
"key": "html",
- "value": "<script>\n(function () {\n if (window.__ctDetectTally) return;\n window.__ctDetectTally = true;\n window.dataLayer = window.dataLayer || [];\n\n function fireConversion(formId, formName) {\n window.dataLayer.push({\n event: 'tally_form_submitted',\n form_id: formId || '',\n form_name: formName || ''\n });\n }\n\n function parseMessageData(data) {\n if (!data) return null;\n if (typeof data === 'string') {\n try {\n return JSON.parse(data);\n } catch (e) {\n return null;\n }\n }\n if (typeof data === 'object') return data;\n return null;\n }\n\n var TALLY_ORIGIN_PATTERN = /(^|\\.)tally\\.so$/;\n\n function isTrustedOrigin(event) {\n if (!event) return false;\n if (event.source === window) return false;\n if (!event.source) return false;\n if (!event.origin || typeof event.origin !== 'string') return false;\n var hostMatch = /^https:\\/\\/([^/]+)/.exec(event.origin);\n if (!hostMatch) return false;\n return TALLY_ORIGIN_PATTERN.test(hostMatch[1]);\n }\n\n function handleMessage(event) {\n try {\n if (!event || !event.data) return;\n var msg = parseMessageData(event.data);\n if (!msg) return;\n var eventName = msg.event || msg.type;\n if (eventName !== 'Tally.FormSubmitted') return;\n if (!isTrustedOrigin(event)) return;\n\n var payload = msg.payload || msg.data || msg;\n if (!payload || typeof payload !== 'object' || !Array.isArray(payload.fields)) return;\n\n fireConversion(payload.formId, payload.formName);\n } catch (e) {\n // Never throw back into the page's own message handling.\n }\n }\n\n if (typeof window !== 'undefined' && window.addEventListener) {\n window.addEventListener('message', handleMessage, false);\n }\n})();\n</script>"
+ "value": "<script>\n/* Tally Submission Listener. Reads only the envelope of Tally's\n * own submission message; it does not decode or read answer values and never\n * pushes answers. */\n(function () {\n 'use strict';\n if (window.__ctDetectTally || window.__ctTallyMethod2Installed) return;\n window.__ctDetectTally = true;\n // Keep the historical Method 2 marker as a one-way compatibility alias.\n // The separate Method 2 adapter has its own marker and can still register\n // after this core is already installed.\n window.__ctTallyMethod2Installed = true;\n window.dataLayer = window.dataLayer || [];\n\n function isWs(c) { return c === ' ' || c === '\\n' || c === '\\r' || c === '\\t'; }\n function skipWs(s, p) { while (p.i < s.length && isWs(s.charAt(p.i))) p.i++; }\n function stringEnd(s, p, decode) {\n if (s.charAt(p.i) !== '\"') throw new Error('string');\n var start = p.i++;\n while (p.i < s.length) {\n var c = s.charAt(p.i++);\n if (c === '\"') {\n if (!decode) return null;\n // Decode only object keys and allowlisted envelope metadata strings.\n return JSON.parse(s.slice(start, p.i));\n }\n if (c.charCodeAt(0) < 0x20) throw new Error('control');\n if (c === '\\\\') {\n if (p.i >= s.length) throw new Error('escape end');\n var esc = s.charAt(p.i++);\n if ('\"\\\\/bfnrt'.indexOf(esc) !== -1) continue;\n if (esc !== 'u' || !/^[0-9a-fA-F]{4}$/.test(s.slice(p.i, p.i + 4))) throw new Error('escape');\n p.i += 4;\n }\n }\n throw new Error('unterminated');\n }\n function skipValue(s, p, depth) {\n if (depth > 32) throw new Error('depth');\n skipWs(s, p);\n var c = s.charAt(p.i);\n if (c === '\"') { stringEnd(s, p, false); return; }\n if (c === '{') {\n p.i++; skipWs(s, p); if (s.charAt(p.i) === '}') { p.i++; return; }\n while (p.i < s.length) {\n skipWs(s, p); stringEnd(s, p, false); skipWs(s, p);\n if (s.charAt(p.i++) !== ':') throw new Error('colon');\n skipValue(s, p, depth + 1); skipWs(s, p);\n var sep = s.charAt(p.i++); if (sep === '}') return; if (sep !== ',') throw new Error('object');\n }\n throw new Error('object end');\n }\n if (c === '[') {\n p.i++; skipWs(s, p); if (s.charAt(p.i) === ']') { p.i++; return; }\n while (p.i < s.length) {\n skipValue(s, p, depth + 1); skipWs(s, p);\n var a = s.charAt(p.i++); if (a === ']') return; if (a !== ',') throw new Error('array');\n }\n throw new Error('array end');\n }\n var begin = p.i;\n while (p.i < s.length && !isWs(s.charAt(p.i)) && ',}]'.indexOf(s.charAt(p.i)) === -1) p.i++;\n if (p.i === begin) throw new Error('value');\n var token = s.slice(begin, p.i);\n if (token !== 'true' && token !== 'false' && token !== 'null' &&\n !/^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(token)) throw new Error('primitive');\n }\n function readStringValue(s, p) { skipWs(s, p); return stringEnd(s, p, true); }\n function readMetadataObject(s, p, wanted, out) {\n skipWs(s, p); if (s.charAt(p.i++) !== '{') throw new Error('metadata object');\n skipWs(s, p); if (s.charAt(p.i) === '}') { p.i++; return; }\n while (p.i < s.length) {\n skipWs(s, p); var key = stringEnd(s, p, true); skipWs(s, p);\n if (s.charAt(p.i++) !== ':') throw new Error('metadata colon');\n if (wanted[key]) { out[key] = readStringValue(s, p); }\n else if (key === 'fields') { skipWs(s, p); if (s.charAt(p.i) !== '[') throw new Error('fields shape'); skipValue(s, p, 0); out.fieldsArray = true; }\n else skipValue(s, p, 0);\n skipWs(s, p); var sep = s.charAt(p.i++); if (sep === '}') return; if (sep !== ',') throw new Error('metadata separator');\n }\n throw new Error('metadata end');\n }\n function readEnvelope(s) {\n if (typeof s !== 'string' || s.length > 1048576) return null;\n var p = { i: 0 }, out = {}, payload = {};\n try {\n skipWs(s, p); if (s.charAt(p.i++) !== '{') return null;\n skipWs(s, p); if (s.charAt(p.i) === '}') return null;\n while (p.i < s.length) {\n skipWs(s, p); var key = stringEnd(s, p, true); skipWs(s, p);\n if (s.charAt(p.i++) !== ':') return null;\n if (key === 'event') out.event = readStringValue(s, p);\n else if (key === 'payload') readMetadataObject(s, p, { id: true, formId: true }, payload);\n else skipValue(s, p, 0);\n skipWs(s, p); var sep = s.charAt(p.i++); if (sep === '}') break; if (sep !== ',') return null;\n }\n skipWs(s, p); if (p.i !== s.length) return null;\n if (out.event !== 'Tally.FormSubmitted') return null;\n if (!payload.id || !payload.formId || !payload.fieldsArray || !/^[-A-Za-z0-9_]{1,128}$/.test(payload.id) || !/^[-A-Za-z0-9_]{1,128}$/.test(payload.formId)) return null;\n return { id: payload.id, formId: payload.formId };\n } catch (e) { return null; }\n }\n function isTallyOrigin(origin) {\n return typeof origin === 'string' && /^https:\\/\\/tally\\.so(?::443)?$/i.test(origin);\n }\n // Bind only fixed-host iframe paths using CSS attribute selectors. Do not\n // retrieve src or data-tally-src: either may contain prefilled respondent\n // data in its query. Only a materialized iframe src is supported here; a\n // deferred attribute without a loaded src fails closed.\n function frameFormId(frame, expectedFormId) {\n if (!/^[-A-Za-z0-9_]{1,128}$/.test(expectedFormId || '') ||\n !frame || typeof frame.matches !== 'function') return '';\n var found = false;\n var modes = ['embed', 'r', 'popup'];\n for (var i = 0; i < modes.length; i++) {\n var base = 'https://tally.so/' + modes[i] + '/' + expectedFormId;\n var selectors = [\n 'iframe[src=\"' + base + '\"]',\n 'iframe[src^=\"' + base + '?\"]',\n 'iframe[src^=\"' + base + '#\"]'\n ];\n for (var j = 0; j < selectors.length; j++) {\n try { if (frame.matches(selectors[j])) { found = true; break; } }\n catch (e) { return ''; }\n }\n if (found) return expectedFormId;\n }\n return '';\n }\n function renderedFrameFormId(source, expectedFormId) {\n if (!source || source === window) return '';\n var frames;\n try { frames = document.getElementsByTagName('iframe'); } catch (e) { return ''; }\n for (var i = 0; frames && i < frames.length; i++) {\n try {\n if (frames[i].contentWindow === source) {\n // The event carries only a bounded public form ID. The selector tests\n // the fixed-host path and exact delimiter without exposing the URL.\n return frameFormId(frames[i], expectedFormId);\n }\n } catch (e) {}\n }\n return '';\n }\n var seen = Object.create(null);\n window.addEventListener('message', function (event) {\n try {\n if (!event || !isTallyOrigin(event.origin)) return;\n var verdict = readEnvelope(event.data);\n if (!verdict) return;\n var configuredFormId = renderedFrameFormId(event.source, verdict.formId);\n if (!configuredFormId || verdict.formId !== configuredFormId) return;\n var key = verdict.formId + ':' + verdict.id;\n if (seen[key]) return;\n seen[key] = true;\n var handled = false;\n var adapter = window.__ctTallyMethod2Handler;\n if (typeof adapter === 'function') {\n try { handled = adapter(event, verdict) === true; } catch (e) { handled = false; }\n }\n if (!handled) window.dataLayer.push({ event: 'tally_form_submitted', form_id: verdict.formId, submission_id: verdict.id });\n } catch (e) {}\n }, false);\n})();\n</script>"
},
{
"type": "BOOLEAN",
diff --git a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-webflow-forms.json b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-webflow-forms.json
index 1f6b172..e65f369 100644
--- a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-webflow-forms.json
+++ b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-webflow-forms.json
@@ -29,7 +29,7 @@
{
"type": "TEMPLATE",
"key": "html",
- "value": "<script>\n(function () {\n if (window.__ctDetectWebflowForms) return;\n window.__ctDetectWebflowForms = true;\n window.dataLayer = window.dataLayer || [];\n\n // How long after a submit we keep watching for Webflow's success box\n // before giving up. Webflow's AJAX round-trip is normally 1\u20132 seconds.\n var WATCH_TIMEOUT_MS = 30000;\n\n function fireConversion(formName) {\n window.dataLayer.push({\n event: 'webflow_form_submitted',\n form_name: formName || ''\n });\n }\n\n // Webflow marks every form component with the `.w-form` wrapper class,\n // regardless of theme or custom classes added on top. This is the same\n // check the production module uses to scope its listener to real Webflow\n // forms (and not e.g. a hand-coded <form> elsewhere on the page).\n function isWebflowForm(formEl) {\n if (!formEl || !formEl.closest) return false;\n return formEl.closest('.w-form') !== null;\n }\n\n function isVisible(el) {\n if (!el) return false;\n try {\n return window.getComputedStyle(el).display !== 'none';\n } catch (e) {\n return false;\n }\n }\n\n // Arm a success watcher for one form. Fires only when Webflow's own\n // success box (`.w-form-done`, a sibling of the form inside the `.w-form`\n // wrapper) becomes visible \u2014 Webflow sets inline `display: block` on it\n // after its AJAX call succeeds (live-verified). A visible `.w-form-fail`\n // (Webflow's failure box), or the timeout elapsing with neither box shown\n // (Webflow's JS can also reject a submission silently, with no UI change\n // at all), tears the watcher down WITHOUT firing. One watcher per form:\n // a re-submit while armed (e.g. a retry after a failure) resets it.\n function armWatcher(formEl, formName) {\n var wrap = formEl.closest('.w-form');\n if (!wrap) return;\n var doneEl = wrap.querySelector('.w-form-done');\n var failEl = wrap.querySelector('.w-form-fail');\n if (!doneEl) return; // nothing to confirm success against \u2014 never fire unconfirmed\n\n var prev = formEl.__ctDetectWatch;\n if (prev) prev.teardown();\n\n var state = { fired: false };\n var observer = null;\n var pollTimer = null;\n var killTimer = null;\n\n function teardown() {\n if (state.fired) return;\n state.fired = true;\n if (observer) { try { observer.disconnect(); } catch (e) {} }\n if (pollTimer) clearInterval(pollTimer);\n if (killTimer) clearTimeout(killTimer);\n formEl.__ctDetectWatch = null;\n }\n state.teardown = teardown;\n\n function check() {\n if (state.fired) return;\n if (isVisible(doneEl)) {\n teardown();\n fireConversion(formName); // confirmed Webflow success\n } else if (isVisible(failEl)) {\n teardown(); // confirmed Webflow failure \u2014 no conversion\n }\n }\n\n if (typeof MutationObserver === 'function') {\n observer = new MutationObserver(check);\n observer.observe(wrap, {\n attributes: true,\n attributeFilter: ['style', 'class'],\n subtree: true,\n childList: true\n });\n }\n pollTimer = setInterval(check, 300); // belt-and-braces alongside the observer\n killTimer = setTimeout(teardown, WATCH_TIMEOUT_MS);\n\n formEl.__ctDetectWatch = state;\n }\n\n // Attached at the document level in CAPTURE phase so it runs before the\n // handler Webflow attaches in bubble phase \u2014 the same technique the\n // production module uses to see the submit reliably. The submit itself\n // never fires the conversion; it only snapshots the form name and arms\n // the success watcher above.\n function handleSubmit(event) {\n try {\n var formEl = event.target;\n if (!formEl || (formEl.tagName || '').toLowerCase() !== 'form') return;\n if (!isWebflowForm(formEl)) return;\n\n // The form's own name/id \u2014 set by the site builder in the Webflow\n // Designer, not user-submitted data. Snapshotted at submit time.\n var formName = formEl.getAttribute('data-name') || formEl.id || '';\n\n armWatcher(formEl, formName);\n } catch (e) {\n // Never throw back into Webflow's own form handling.\n }\n }\n\n if (typeof document !== 'undefined' && document.addEventListener) {\n document.addEventListener('submit', handleSubmit, true);\n }\n})();\n</script>"
+ "value": "<script>\n(function () {\n if (window.__ctWebflowForms) return;\n window.__ctWebflowForms = true;\n window.dataLayer = window.dataLayer || [];\n var listeners = [], timeout = 30000;\n window.__ctWebflowSubscribe = function (listener) {\n if (listener && typeof listener === 'object') listeners.push(listener);\n };\n function isForm(form) {\n try { return !!(form && String(form.tagName || '').toLowerCase() === 'form' && form.closest && form.closest('.w-form')); }\n catch (e) { return false; }\n }\n function notify(phase, form, candidate) {\n var handled = false;\n for (var i=0;i<listeners.length;i++) {\n try { var fn=listeners[i] && listeners[i][phase]; if (typeof fn==='function' && fn(form,candidate)===true) handled=true; } catch(e) {}\n }\n return handled;\n }\n function visible(el) { try { return !!el && window.getComputedStyle(el).display !== 'none'; } catch(e) { return false; } }\n function emit(form) {\n var name=''; try { name=form.getAttribute('data-name') || form.id || ''; } catch(e) {}\n if (!notify('onCandidate', form, true)) window.dataLayer.push({event:'webflow_form_submitted',form_name:name});\n }\n function submit(event) {\n try {\n var form=event.target; if (!isForm(form)) return;\n notify('beforeAttempt', form, false);\n var wrap=form.closest('.w-form'), done=wrap.querySelector('.w-form-done'), fail=wrap.querySelector('.w-form-fail');\n if (!done) return;\n var old=form.__ctWebflowWatch;\n if (old) { notify('onOverlap', form, false); old.cancel(false); form.__ctWebflowWatch=null; }\n var staleFail=visible(fail), settled=false, observer=null, poll=null, kill=null, jq=window.jQuery;\n function stop(rejected) { if(settled)return; settled=true; if(observer)try{observer.disconnect();}catch(e){} if(jq)jq(document).off('ajaxComplete',check); if(poll)clearInterval(poll); if(kill)clearTimeout(kill); if(form.__ctWebflowWatch===state)form.__ctWebflowWatch=null; if(rejected)notify('onRejected',form,false); }\n var state={cancel:function(){stop(false);}};\n function check() {\n if(settled)return;\n // Webflow sets success only after its server accepts the form. A redirect\n // skips the success box, so check that state after its AJAX callback.\n var wf=jq && jq(form).data('.w-form');\n if(wf && wf.form && wf.form[0]===form && wf.redirect && wf.success===true){ stop(); emit(form); return; }\n if(visible(done)){ stop(); emit(form); return; }\n if(!visible(fail)){staleFail=false;return;}\n if(!staleFail)stop(true);\n }\n if(typeof MutationObserver==='function'){observer=new MutationObserver(check);observer.observe(wrap,{attributes:true,attributeFilter:['style','class'],subtree:true,childList:true});}\n if(jq)jq(document).on('ajaxComplete',check);\n poll=setInterval(check,300); kill=setTimeout(function(){stop(true);},timeout); form.__ctWebflowWatch=state;\n } catch(e) {}\n }\n if(typeof document!=='undefined'&&document.addEventListener)document.addEventListener('submit',submit,true);\n})();\n</script>"
},
{
"type": "BOOLEAN",
diff --git a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-wpforms.json b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-wpforms.json
index dae3783..a13d499 100644
--- a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-wpforms.json
+++ b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-wpforms.json
@@ -29,7 +29,7 @@
{
"type": "TEMPLATE",
"key": "html",
- "value": "<script>\n(function () {\n if (window.__ctDetectWpforms) return;\n window.__ctDetectWpforms = true;\n // Only run in real http(s) documents. about:blank / srcdoc iframes inherit\n // the parent's origin, so they SHARE sessionStorage \u2014 a copy of this script\n // running in one would consume the deferred native-mode marker and, because\n // its pathname can never equal the form page's path, fabricate a fire via\n // the redirect heuristic. Observed live on parkhousesoftware.com (an\n // about:blank iframe stole the marker during verification, 2026-07-05).\n if (!/^https?:$/.test(window.location.protocol)) return;\n window.dataLayer = window.dataLayer || [];\n\n var NATIVE_WINDOW_MS = 10000;\n var DEFERRED_MARKER_KEY = '__ctDetectWpformsNativePending';\n var DEFERRED_MARKER_TTL_MS = 60000;\n\n function isWPForm(formEl) {\n if (!formEl) return false;\n try {\n if (formEl.closest && formEl.closest('.wpforms-container')) return true;\n } catch (e) {\n // .closest not available \u2014 fall back to ID check\n }\n var id = formEl.id || '';\n return /^wpforms-form-\\d+$/.test(id);\n }\n\n function parseFormId(formEl) {\n var id = (formEl && formEl.id) || '';\n var m = /^wpforms-form-(\\d+)$/.exec(id);\n return m ? m[1] : '';\n }\n\n function fireConversion(formId) {\n window.dataLayer.push({\n event: 'wpforms_form_submitted',\n form_id: formId || ''\n });\n }\n\n // ---- Shared validation-marker check (used by both fire paths) ----\n\n function isNodeHidden(el) {\n try {\n if (el.hidden) return true;\n if (el.getAttribute && el.getAttribute('aria-hidden') === 'true') return true;\n var view = el.ownerDocument && el.ownerDocument.defaultView;\n if (view && view.getComputedStyle) {\n var cs = view.getComputedStyle(el);\n if (cs && (cs.display === 'none' || cs.visibility === 'hidden')) return true;\n }\n } catch (e) {\n // fall through\n }\n return false;\n }\n\n function hasVisibleValidationErrors(scopeEl) {\n if (!scopeEl || !scopeEl.querySelectorAll) return false;\n try {\n var nodes = scopeEl.querySelectorAll(\n '.wpforms-error, .wpforms-error-container, [aria-invalid=\"true\"]'\n );\n for (var i = 0; i < nodes.length; i++) {\n var node = nodes[i];\n if (isNodeHidden(node)) continue;\n if (node.getAttribute && node.getAttribute('aria-invalid') === 'true') return true;\n if ((node.textContent || '').trim()) return true;\n }\n } catch (e) {\n // fall through\n }\n return false;\n }\n\n function hasServerRejectionMarkers() {\n try {\n var wrappers = document.querySelectorAll('.wpforms-container');\n for (var i = 0; i < wrappers.length; i++) {\n if (hasVisibleValidationErrors(wrappers[i])) return true;\n }\n } catch (e) {\n // fall through\n }\n return false;\n }\n\n function hasConfirmationMessage() {\n try {\n var nodes = document.querySelectorAll(\n '.wpforms-confirmation-container-full, .wpforms-confirmation-container, div[id^=\"wpforms-confirmation-\"]'\n );\n for (var i = 0; i < nodes.length; i++) {\n if (isNodeHidden(nodes[i])) continue;\n if ((nodes[i].textContent || '').trim()) return true;\n }\n } catch (e) {\n // fall through\n }\n return false;\n }\n\n // ---- Fire path 1: AJAX success event ----\n\n var activeWatchers = [];\n\n function findWatcher(formEl) {\n for (var w = 0; w < activeWatchers.length; w++) {\n if (activeWatchers[w].form === formEl) return activeWatchers[w];\n }\n return null;\n }\n\n // An AJAX success disarms any pagehide watcher armed for this form \u2014 the\n // 2s dedup flag self-clears but the native watcher would otherwise stay\n // armed for the full 10s window and could re-fire on a later navigation.\n function disarmWatcher(formEl) {\n var existing = findWatcher(formEl);\n if (existing && typeof existing.cleanup === 'function') existing.cleanup();\n }\n\n var successHooked = false;\n\n function hookWpformsSuccess() {\n if (successHooked) return true;\n if (typeof jQuery === 'undefined' && typeof $ === 'undefined') return false;\n\n var jQ = typeof jQuery !== 'undefined' ? jQuery : $;\n jQ(document).on('wpformsAjaxSubmitSuccess', function (event) {\n var formEl = event.target;\n if (!formEl) return;\n\n if (formEl.getAttribute('data-ct-processing') === 'true') return;\n formEl.setAttribute('data-ct-processing', 'true');\n setTimeout(function () { formEl.removeAttribute('data-ct-processing'); }, 2000);\n\n disarmWatcher(formEl);\n fireConversion(parseFormId(formEl));\n });\n successHooked = true;\n return true;\n }\n\n // ---- Fire path 2: native (non-AJAX) pagehide watcher + deferred verdict ----\n\n function writeDeferredMarker(formId) {\n try {\n window.sessionStorage.setItem(DEFERRED_MARKER_KEY, JSON.stringify({\n t: Date.now(),\n path: window.location.pathname,\n formId: formId\n }));\n return true;\n } catch (e) {\n return false;\n }\n }\n\n function takeDeferredMarker() {\n try {\n var raw = window.sessionStorage.getItem(DEFERRED_MARKER_KEY);\n if (!raw) return null;\n window.sessionStorage.removeItem(DEFERRED_MARKER_KEY);\n var data = JSON.parse(raw);\n if (!data || typeof data !== 'object') return null;\n if (!data.t || Date.now() - data.t > DEFERRED_MARKER_TTL_MS) return null;\n return data;\n } catch (e) {\n try { window.sessionStorage.removeItem(DEFERRED_MARKER_KEY); } catch (e2) {}\n return null;\n }\n }\n\n // Runs once at module init on every page load. Consumes the marker the\n // previous page wrote at pagehide (if any) and reads the verdict from the\n // markup WPForms rendered into THIS page. Rejection is checked first: the\n // rejected-POST re-render always carries error markers, so a missed fire\n // here degrades to under-counting, never fabricating.\n function processDeferredVerdict() {\n var marker = takeDeferredMarker();\n if (!marker) return;\n\n if (hasServerRejectionMarkers()) return;\n\n if (hasConfirmationMessage()) {\n fireConversion(marker.formId);\n return;\n }\n // No WPForms markup either way. A success configured to redirect lands\n // on a different path with no confirmation container \u2014 treat a changed\n // pathname as that redirect. A rejection can't look like this: the\n // rejected POST always re-renders the form WITH error markers.\n if (marker.path && window.location.pathname !== marker.path) {\n fireConversion(marker.formId);\n }\n // Same page, no markers either way \u2014 ambiguous, do not fire.\n }\n\n function watchForSuccess(formEl, formId, pagehideTrusted) {\n var entry = { form: formEl, refresh: refresh, cleanup: cleanup };\n activeWatchers.push(entry);\n\n var fired = false;\n var timer = null;\n var pagehideArmed = false;\n\n function onPageHide() {\n if (fired) return;\n // Click-then-leave guard: a visitor who submitted an invalid form,\n // got blocked, then navigated away produces a pagehide too. Visible\n // error markers mean the submit never went through \u2014 do not fire.\n if (hasVisibleValidationErrors(formEl)) return;\n fired = true;\n if (formEl.getAttribute('data-ct-processing') !== 'true') {\n writeDeferredMarker(formId);\n }\n cleanup();\n }\n\n function armPagehide() {\n if (pagehideArmed) return;\n try {\n window.addEventListener('pagehide', onPageHide, true);\n pagehideArmed = true;\n } catch (e) {\n // fall through\n }\n }\n\n function disarmPagehide() {\n if (!pagehideArmed) return;\n try { window.removeEventListener('pagehide', onPageHide, true); } catch (e) {}\n pagehideArmed = false;\n }\n\n function startTimer() {\n if (timer) clearTimeout(timer);\n // No navigation within the window \u2192 either AJAX already fired (page\n // stayed) or the submit was abandoned/rejected. Either way: clean up,\n // do not fire.\n timer = setTimeout(function () {\n if (!fired) cleanup();\n }, NATIVE_WINDOW_MS);\n }\n\n function cleanup() {\n if (timer) { clearTimeout(timer); timer = null; }\n disarmPagehide();\n var idx = activeWatchers.indexOf(entry);\n if (idx !== -1) activeWatchers.splice(idx, 1);\n }\n\n // A later submit on the same form refreshes the snapshot + verdict +\n // timer \u2014 a visitor who failed validation, fixed it, and re-submitted\n // inside the window is a fresh attempt.\n function refresh(nextFormId, nextPagehideTrusted) {\n if (fired) return;\n formId = nextFormId;\n if (nextPagehideTrusted) armPagehide();\n else disarmPagehide();\n startTimer();\n }\n\n // Only arm pagehide when the form was client-valid at submit time. An\n // invalid form cannot have submitted, so its pagehide must not confirm.\n if (pagehideTrusted) armPagehide();\n startTimer();\n }\n\n // Bubble-through-capture submit handler: arms the native watcher on every\n // WPForms submit attempt. This fires even when WPForms preventDefaults the\n // submit (the event still dispatches) \u2014 this is the moment we snapshot,\n // NOT the moment we fire. Capture phase is required: WPForms' own submit\n // handler stops the event's propagation before it reaches a bubble-phase\n // document listener (verified on a live form in the production module).\n function armNativeWatcher(event) {\n var formEl = event.target;\n if (!formEl || (formEl.tagName || '').toLowerCase() !== 'form') return;\n if (!isWPForm(formEl)) return;\n\n var formId = parseFormId(formEl);\n\n // Client-validity gate: only trust the pagehide path when the form is\n // valid (or checkValidity is unavailable). An invalid form cannot have\n // submitted, so its navigation must not be read as a success.\n var pagehideTrusted = true;\n try {\n if (typeof formEl.checkValidity === 'function' && formEl.checkValidity() === false) {\n pagehideTrusted = false;\n }\n } catch (e) {\n // constraint validation unavailable \u2014 the visible-error check at\n // pagehide time still guards this path\n }\n\n var existing = findWatcher(formEl);\n if (existing) {\n existing.refresh(formId, pagehideTrusted);\n return;\n }\n\n watchForSuccess(formEl, formId, pagehideTrusted);\n }\n\n document.addEventListener('submit', armNativeWatcher, true);\n\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', function () {\n processDeferredVerdict();\n });\n } else {\n processDeferredVerdict();\n }\n\n hookWpformsSuccess();\n if (!successHooked) {\n document.addEventListener('DOMContentLoaded', function () {\n hookWpformsSuccess();\n });\n window.addEventListener('load', function () {\n hookWpformsSuccess();\n });\n }\n})();\n</script>"
+ "value": "<script>\n/* WPForms listener. Records message and redirect confirmations.\n * Native redirects use a short-lived submission marker and changed pathname.\n * Does not read form values, labels, rendered text/HTML, response bodies,\n * redirect URLs, or URL query strings. */\n(function () {\n 'use strict';\n if (window.__ctDetectWpforms) return;\n window.__ctDetectWpforms = true;\n if (!/^https?:$/.test(window.location.protocol)) return;\n window.dataLayer = window.dataLayer || [];\n\n var PENDING_KEY = '__ctWpformsNativePendingV1';\n var PENDING_TTL_MS = 120000;\n\n function formId(form) {\n var match = /^wpforms-form-(\\d+)$/.exec((form && form.id) || '');\n return match ? match[1] : null;\n }\n function confirmationNode(id) {\n if (!id || !/^\\d+$/.test(id)) return null;\n try { return document.querySelector('#wpforms-confirmation-' + id); } catch (e) { return null; }\n }\n // A delayed callback can run after another callback has already observed\n // the same inserted node. Deduplicate by node identity, not by form ID, so\n // a later accepted response with a distinct confirmation node still counts.\n var supportsWeakSet = typeof WeakSet === 'function';\n var handledConfirmationNodes = supportsWeakSet ? new WeakSet() : [];\n function markConfirmationSeen(node) {\n if (supportsWeakSet) {\n if (handledConfirmationNodes.has(node)) return false;\n handledConfirmationNodes.add(node);\n return true;\n }\n if (handledConfirmationNodes.indexOf(node) !== -1) return false;\n handledConfirmationNodes.push(node);\n return true;\n }\n function push(id) {\n if (!id || !/^\\d+$/.test(id)) return;\n window.dataLayer.push({ event: 'wpforms_form_submitted', form_id: id });\n }\n // Method 2 owns and pushes its enriched payload. The detector sees only a\n // literal handled marker; arbitrary objects or PII are never read/forwarded.\n function emitConfirmed(id, form, mode) {\n var adapter = window.__ctWpformsMethod2Emit;\n try { if (typeof adapter === 'function' && adapter(id, form || null, mode) === true) return; } catch (e) {}\n push(id);\n }\n function discardAdapterSnapshot(id, form, mode) {\n var discard = window.__ctWpformsMethod2Discard;\n try { if (typeof discard === 'function') discard(id, form || null, mode); } catch (e) {}\n }\n function storePending(id) {\n if (!id) return;\n try {\n window.sessionStorage.setItem(PENDING_KEY, JSON.stringify({ id: id, time: Date.now(), path: window.location.pathname }));\n } catch (e) {}\n }\n function takePending() {\n try {\n var raw = window.sessionStorage.getItem(PENDING_KEY);\n if (!raw) return null;\n window.sessionStorage.removeItem(PENDING_KEY);\n var value = JSON.parse(raw);\n if (!value || !/^\\d+$/.test(String(value.id || '')) ||\n typeof value.time !== 'number' || Date.now() - value.time > PENDING_TTL_MS ||\n Date.now() < value.time) return null;\n return { id: String(value.id), path: typeof value.path === 'string' ? value.path : null };\n } catch (e) { return null; }\n }\n function hasVisibleErrors(root) {\n var errors = root.querySelectorAll('.wpforms-error, .wpforms-error-container, [aria-invalid=\"true\"]');\n for (var i = 0; i < errors.length; i++) {\n if (errors[i].getClientRects().length) return true;\n }\n return false;\n }\n function processNativeVerdict() {\n var marker = takePending();\n if (!marker) return;\n if (hasVisibleErrors(document)) discardAdapterSnapshot(marker.id, null, 'native-no-confirmation');\n else if (confirmationNode(marker.id)) emitConfirmed(marker.id, null, 'native-message');\n else if (marker.path && marker.path !== window.location.pathname) {\n // A clean submit followed by a new page is the redirect confirmation.\n // An optional Method 2 adapter may attach what it saved on the form page.\n emitConfirmed(marker.id, null, 'native-redirect');\n }\n else discardAdapterSnapshot(marker.id, null, 'native-no-confirmation');\n }\n\n // Keep one short-lived navigation watcher per form. Client validation can\n // cancel submission, so a submit attempt alone must not leave a marker.\n var nativeWatchers = new WeakMap();\n document.addEventListener('submit', function (event) {\n var form = event && event.target;\n if (!form || (form.tagName || '').toLowerCase() !== 'form') return;\n var id = formId(form);\n if (!id) return;\n var classes = typeof form.className === 'string' ? form.className : '';\n if (/(^|\\s)wpforms-ajax-form(\\s|$)/.test(classes)) return;\n var previous = nativeWatchers.get(form);\n if (previous) previous();\n var timer;\n function cleanup() {\n window.removeEventListener('pagehide', onPageHide, true);\n clearTimeout(timer);\n nativeWatchers.delete(form);\n }\n function onPageHide() {\n cleanup();\n // A corrected retry can still display the previous server error box.\n // Use the current client-validation result, without reading answers.\n var jq = window.jQuery;\n var validator = typeof jq === 'function' ? jq(form).data('validator') : null;\n if (validator && validator.errorList) {\n if (validator.errorList.length) return;\n } else if (hasVisibleErrors(form)) return;\n storePending(id);\n }\n nativeWatchers.set(form, cleanup);\n window.addEventListener('pagehide', onPageHide, true);\n timer = setTimeout(cleanup, 10000);\n }, true);\n\n // AJAX message confirmation: the callback alone is ambiguous. Wait until\n // WPForms has inserted a new, form-attributed confirmation node.\n var jqueryHooked = false;\n var redirectEpochByForm = typeof WeakMap === 'function' ? new WeakMap() : null;\n var seenRedirectEvents = typeof WeakSet === 'function' ? new WeakSet() : [];\n var seenSuccessEvents = typeof WeakSet === 'function' ? new WeakSet() : [];\n function markEventSeen(set, event) {\n if (!event || (typeof event !== 'object' && typeof event !== 'function')) return false;\n if (typeof WeakSet === 'function' && set instanceof WeakSet) {\n if (set.has(event)) return false;\n set.add(event);\n return true;\n }\n if (set.indexOf(event) !== -1) return false;\n set.push(event);\n return true;\n }\n function markRedirectEvent(event) {\n return markEventSeen(seenRedirectEvents, event);\n }\n function hookWpformsEvents() {\n if (jqueryHooked) return;\n var jq = window.jQuery || window.$;\n if (typeof jq !== 'function') return;\n jqueryHooked = true;\n jq(document).on('wpformsAjaxSubmitSuccess.ctWpforms', function (event) {\n if (!markEventSeen(seenSuccessEvents, event)) return;\n var form = event && event.target;\n var id = formId(form);\n if (!id) return;\n var redirectEpoch = redirectEpochByForm ? (redirectEpochByForm.get(form) || 0) : 0;\n var before = confirmationNode(id);\n setTimeout(function () {\n var after = confirmationNode(id);\n if (after && after !== before && markConfirmationSeen(after)) {\n emitConfirmed(id, form, 'ajax-message');\n } else if (!redirectEpochByForm || (redirectEpochByForm.get(form) || 0) === redirectEpoch) {\n discardAdapterSnapshot(id, form, 'ajax-no-confirmation');\n }\n }, 0);\n });\n jq(document).on('wpformsAjaxSubmitFailed.ctWpforms wpformsAjaxSubmitError.ctWpforms wpformsAjaxSubmitActionRequired.ctWpforms', function (event) {\n var form = event && event.target;\n var id = formId(form);\n if (id) discardAdapterSnapshot(id, form, 'ajax-rejected');\n });\n // WPForms 1.6.7 triggers this only after ajax_process_redirect has\n // produced a nonempty redirect_url from accepted processing. The URL and\n // response object are intentionally not inspected.\n jq(document).on('wpformsAjaxSubmitBeforeRedirect.ctWpforms', function (event) {\n if (!markRedirectEvent(event)) return;\n var form = event && event.target;\n var id = formId(form);\n if (!id) return;\n if (redirectEpochByForm) redirectEpochByForm.set(form, (redirectEpochByForm.get(form) || 0) + 1);\n emitConfirmed(id, form, 'ajax-redirect');\n });\n }\n function ready() {\n processNativeVerdict();\n hookWpformsEvents();\n }\n // Let sibling Method 2 tags in the same page task install their enrichment\n // delegate before a native confirmation verdict is dispatched.\n if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', ready, { once: true });\n else setTimeout(ready, 0);\n document.addEventListener('DOMContentLoaded', hookWpformsEvents, { once: true });\n window.addEventListener('load', hookWpformsEvents, { once: true });\n})();\n</script>"
},
{
"type": "BOOLEAN",
diff --git a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-ws-form.json b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-ws-form.json
index 0e04974..ff8b57e 100644
--- a/skills/conversion-tracking/assets/gtm-recipes/detect/detect-ws-form.json
+++ b/skills/conversion-tracking/assets/gtm-recipes/detect/detect-ws-form.json
@@ -29,7 +29,7 @@
{
"type": "TEMPLATE",
"key": "html",
- "value": "<script>\n(function () {\n if (window.__ctDetectWsForm) return;\n window.__ctDetectWsForm = true;\n window.dataLayer = window.dataLayer || [];\n\n function fireConversion(formId) {\n window.dataLayer.push({\n event: 'ws_form_submitted',\n form_id: formId || ''\n });\n }\n\n // Same form-resolution chain the production module uses to find the\n // form element (it just never used it for anything but PII \u2014 here we\n // read a generic, non-PII form_id off whatever it resolves to).\n function resolveForm(event, formObject) {\n var formEl = null;\n try {\n if (formObject && formObject.form_canvas_obj && formObject.form_canvas_obj[0]) {\n formEl = formObject.form_canvas_obj[0].querySelector('form.wsf-form');\n }\n if (!formEl && event && event.target) {\n var target = event.target;\n if ((target.tagName || '').toLowerCase() === 'form') {\n formEl = target;\n } else if (target.querySelector) {\n formEl = target.querySelector('form.wsf-form');\n }\n }\n if (!formEl) {\n formEl = document.querySelector('form.wsf-form');\n }\n } catch (e) {\n // non-fatal \u2014 fall through with whatever we have (possibly null)\n }\n return formEl;\n }\n\n // Fire path \u2014 WS Form's own jQuery event, fired on `document` once an\n // AJAX submission passes server-side validation. This is the ONLY path\n // that ever fires a conversion.\n var successHooked = false;\n\n function hookWsFormSuccess() {\n if (successHooked) return true;\n if (typeof jQuery === 'undefined' && typeof $ === 'undefined') return false;\n\n var jQ = typeof jQuery !== 'undefined' ? jQuery : $;\n jQ(document).on('wsf-success', function (event, formObject) {\n var formEl = resolveForm(event, formObject);\n fireConversion(formEl ? (formEl.id || '') : '');\n });\n successHooked = true;\n return true;\n }\n\n // Retry hooking on DOMContentLoaded and window load \u2014 some sites load\n // jQuery very late.\n if (!hookWsFormSuccess()) {\n document.addEventListener('DOMContentLoaded', function () {\n hookWsFormSuccess();\n });\n window.addEventListener('load', function () {\n hookWsFormSuccess();\n });\n }\n})();\n</script>"
+ "value": "<script>\n(function () {\n if (window.__ctDetectWsForm) return;\n window.__ctDetectWsForm = true;\n window.dataLayer = window.dataLayer || [];\n var seenEvents = typeof WeakSet === 'function' ? new WeakSet() : null;\n var lastSuccessByInstance = {};\n function unwrap(value) { return value && value.jquery ? value[0] : (value && value[0] && value[0].nodeType ? value[0] : value); }\n function onAcceptedSubmit(event, formObject, formId, instanceId, formEl) {\n if (event && seenEvents) {\n if (seenEvents.has(event)) return;\n seenEvents.add(event);\n }\n var form = unwrap(formEl);\n if (!form || !form.matches || !form.matches('form.wsf-form')) return;\n var id;\n if (typeof formId === 'string') {\n if (!/^\\d+$/.test(formId) || Number(formId) < 1) return;\n id = formId;\n } else if (typeof formId === 'number') {\n if (!isFinite(formId) || Math.floor(formId) !== formId || formId < 1) return;\n id = String(formId);\n } else {\n return;\n }\n // WS Form can finish both requests from a double-click. Count the rapid\n // success callbacks once, without changing the form or reading answers.\n var instance = typeof instanceId === 'string' || typeof instanceId === 'number' ? instanceId : '';\n var key = id + ':' + instance;\n var now = Date.now();\n if (lastSuccessByInstance[key] !== undefined && now - lastSuccessByInstance[key] < 2000) return;\n lastSuccessByInstance[key] = now;\n var adapter = window.__ctWsFormMethod2Emit;\n if (typeof adapter === 'function') {\n try { if (adapter(form, id, instanceId) === true) return; }\n catch (e) { return; }\n }\n window.dataLayer.push({ event: 'ws_form_submitted', form_id: id });\n }\n var handlerBound = false;\n function hook() {\n if (handlerBound) return true;\n var jq = typeof jQuery !== 'undefined' ? jQuery : (typeof $ !== 'undefined' ? $ : null);\n if (!jq) return false;\n jq(document).on('wsf-submit-success', onAcceptedSubmit);\n handlerBound = true;\n return true;\n }\n if (!hook()) {\n document.addEventListener('DOMContentLoaded', hook, { once: true });\n window.addEventListener('load', hook, { once: true });\n }\n})();\n</script>"
},
{
"type": "BOOLEAN",
diff --git a/skills/conversion-tracking/assets/snippets/README.md b/skills/conversion-tracking/assets/snippets/README.md
index 96f72cc..a34498f 100644
--- a/skills/conversion-tracking/assets/snippets/README.md
+++ b/skills/conversion-tracking/assets/snippets/README.md
@@ -59,30 +59,30 @@ Not every snippet fires on a confirmed success. Some tools expose no success sig
| Snippet | Signal type | Exact signal |
|---|---|---|
-| `calendly.js` | Native success event | `calendly.event_scheduled` postMessage from calendly.com |
-| `contact-form-7.js` | Native success event | `wpcf7mailsent` DOM event |
-| `divi-forms.js` | DOM-inferred after submit | `.et-pb-contact-message` gains text with no `.et_contact_error` / error-text markers |
-| `elementor-forms.js` | Native success event | jQuery `submit_success` on `document` |
-| `fluent-forms.js` | Native success event | jQuery `fluentform_submission_success` |
-| `formidable-forms.js` | Native success event (AJAX); DOM-inferred after submit (non-AJAX) | `frmFormComplete` / `frmBeforeFormRedirect`; non-AJAX: next page shows `.frm_message` or a redirect, with no error markers |
-| `forminator.js` | Native success event | jQuery `forminator:form:submit:success` |
-| `framer-forms.js` | Submit/click-based best effort | capture-phase `submit` on a Framer form, caught before Framer's own handler cancels it, passing `checkValidity()`; repeats on the same form within 2s are collapsed |
-| `gravity-forms.js` | Native success event | jQuery `gform_confirmation_loaded`, with a MutationObserver fallback on the confirmation message |
-| `jotform.js` | Submission built (`submit` then `formdata`, once per form) for the source-code embed; for the iframe embed, thank-you redirect recommended; message listener kept as fallback | source embed: a capture-phase `submit` marks the form, then the `formdata` event fires once per form ID; iframe: `{action: 'submission-completed', formID}` postMessage, which Jotform doesn't document, counted only from a Jotform iframe on the page showing that form ID, once per form ID |
-| `ninja-forms.js` | Native success event | Radio `forms` channel `submit:response` with no errors, with a MutationObserver fallback |
-| `tally.js` | Native success event | `Tally.FormSubmitted` postMessage from tally.so |
+| `calendly.js` | Native success event | `calendly.event_scheduled` postMessage with origin `https://calendly.com`, accepted only from a connected `iframe[src^="https://calendly.com/"]` and only when its event and invitee `scheduled_events` URIs name the same event; once per event and invitee pair |
+| `contact-form-7.js` | Native success event | `wpcf7mailsent` DOM event on a CF7 form with a numeric form ID; overlapping requests from one attempt (a repeat `wpcf7beforesubmit` while the form is still `submitting`) count once |
+| `divi-forms.js` | DOM-inferred after submit | an `.et_pb_contact_form_container` shows `.et-pb-contact-message.et_pb_success_message` after Divi's response has removed `form.et_pb_contact_form`, with no `.et_pb_contact_error_meesage` (Divi's spelling) or `.et_contact_error`; once per message node |
+| `elementor-forms.js` | Native success event | jQuery `submit_success` on `document` from a `form.elementor-form` that has an ID, a name other than `New Form`, or a widget `data-id`; each event counted once |
+| `fluent-forms.js` | Native success event | jQuery `fluentform_submission_success` carrying a Fluent form and a `response` object; once per response object and form, since Fluent sends one success through three events |
+| `formidable-forms.js` | Native success event (AJAX); DOM-inferred after submit (non-AJAX) | jQuery `frmFormComplete` / `frmBeforeFormRedirect`, once per response object; non-AJAX: a submit leaves a sessionStorage marker on page exit, then within 60s the next page shows `.frm_message` in `#frm_form_<id>_container`, or a same-site path change with the form gone, with no `.frm_error` / `.frm_blank_field` markers |
+| `forminator.js` | Native success event (AJAX); DOM-inferred after submit (non-AJAX) | jQuery `forminator:form:submit:success` from a `form.forminator-custom-form`, each event counted once; non-AJAX: a visible `.forminator-response-message.forminator-success` inside a form without `forminator_ajax` on the returned page, once per form |
+| `framer-forms.js` | DOM-inferred after submit | Framer's own form request: each OK response to a `fetch` POST to `api.framer.com/forms/v1/forms/<id>/submit` fires once (the snippet wraps `window.fetch`, so it must load before the submit); a capture-phase `submit`, or Enter in a valid Framer form, in the previous 60s only supplies `form_name`, left empty when several forms are pending |
+| `gravity-forms.js` | Native success event; DOM-inferred after submit (builds without `gform.utils`) | `gform/ajax/post_ajax_submission` result with `success`, `is_valid`, `submission_type` `submit`, `is_spam` false and a positive `entry_id`, once per form and entry ID (the snippet switches non-AJAX and iframe submits to Gravity's AJAX); older builds: submit or `gform_submit_button_` click, then jQuery `gform_confirmation_loaded`, the AJAX iframe's postback or a visible `gform_confirmation_message_<id>`, or after a reload that form's confirmation within 60s with no validation errors; once per attempt |
+| `jotform.js` | Native success event | `{action: 'submission-completed', formID}` postMessage from `https://form.jotform.com` or `https://submit.jotform.com`, accepted only from an iframe on the page whose `form.jotform.com/<id>` address matches the form ID; once per iframe until the page reloads. Covers the iframe and script embeds, not the full source-code embed |
+| `ninja-forms.js` | Native success event | Radio `forms` channel `submit:response` with empty `errors`, no `halt`, a `form_id` matching the callback's and a saved entry ID (`actions.save.sub_id`, so the form needs its Record Submission action); once per entry ID, with no DOM fallback |
+| `tally.js` | Native success event | `Tally.FormSubmitted` postMessage from `https://tally.so`, accepted only from a loaded `tally.so/embed`, `/r` or `/popup` iframe for the same form ID, with a submission `id` and a `fields` array; once per form and submission ID |
| `typeform.js` | Native success event | `form-submit` postMessage from typeform.com carrying `formId` and `responseId` |
-| `webflow-forms.js` | DOM-inferred after submit | `.w-form-done` becomes visible within 30s of submit (`.w-form-fail` or timeout cancels) |
+| `webflow-forms.js` | DOM-inferred after submit | submit on a form in `.w-form`, then within 30s `.w-form-done` becomes visible, or Webflow's own form state shows a redirect with `success === true` (checked on jQuery `ajaxComplete`); a newly shown `.w-form-fail` or the timeout cancels, and a resubmit replaces the pending watch |
| `wix-forms.js` | DOM-inferred after submit (new forms); submit/click-based best effort (old forms) | new: Submit click, then a success status/cleared form with no visible errors within 7s, or a page unload after a valid click; old: `submit` passing `checkValidity()` |
| `wix-scheduling.js` | DOM-inferred after submit | Book Now click stored in localStorage, then the `ThankYouPageAppDataHook.root` confirmation page renders within 10 minutes |
-| `wpforms.js` | Native success event (AJAX); DOM-inferred after submit (non-AJAX) | jQuery `wpformsAjaxSubmitSuccess`; non-AJAX: next page shows the confirmation container or a redirect, with no error markers |
-| `ws-form.js` | Native success event | jQuery `wsf-success` |
+| `wpforms.js` | Native success event (AJAX); DOM-inferred after submit (non-AJAX) | jQuery `wpformsAjaxSubmitSuccess` followed by a new `#wpforms-confirmation-<id>` node (once per node), or `wpformsAjaxSubmitBeforeRedirect`; non-AJAX: leaving the page within 10s of submit with no client validation errors stores a sessionStorage marker, then within 120s the next page shows `#wpforms-confirmation-<id>` or a different path, with no `.wpforms-error` / `[aria-invalid]` markers |
+| `ws-form.js` | Native success event | jQuery `wsf-submit-success` on a `form.wsf-form` with a numeric form ID; repeats for the same form and instance within 2s count once |
| `phone-click.js` | Submit/click-based best effort | click on an `a[href^="tel:"]` (call intent, not a completed call) |
| `file-download.js` | Submit/click-based best effort | click on a link to a downloadable file extension |
| `thank-you-page.js` | DOM-inferred after submit | page path starts with a configured confirmation path |
| `generic-ajax-form.js` | DOM-inferred after submit | a success message appears within 7s of submit with no visible validation error |
-**Jotform note.** Use one method per form, either the thank-you redirect with `thank-you-page.js` or this snippet, never both. The source-code path was tested on a classic form, where a submit Jotform's validation rejects doesn't fire. Payment, multi-page, save-and-continue and captcha forms are untested, so prefer the redirect for those.
+**Jotform note.** Use one method per form, either the thank-you redirect with `thank-you-page.js` or this snippet, never both. This snippet covers Jotform's iframe and script embeds, where Jotform sends the page a completion message, and passed live checks on both, including a submission Jotform's validation rejected. It doesn't cover the full source-code embed, which sends no such message, so use the redirect there. Payment, multi-page, save-and-continue and captcha forms are untested, so prefer the redirect for those too.
**PII note for `phone-click.js`.** It pushes the clicked number (`phone_number`) and the link text (`link_text`) to the dataLayer, and any tag can forward those. That is fine for a business's own published numbers. If a page shows visitor-specific numbers (an account page, a "your rep" number pulled from a CRM), remove those two fields from the push before installing.
diff --git a/skills/conversion-tracking/assets/snippets/calendly.js b/skills/conversion-tracking/assets/snippets/calendly.js
index 35f1db9..32e0d2d 100644
--- a/skills/conversion-tracking/assets/snippets/calendly.js
+++ b/skills/conversion-tracking/assets/snippets/calendly.js
@@ -2,47 +2,110 @@
* Detects: meeting booked. Pushes dataLayer event: calendly_event_scheduled
* From the conversion-tracking skill in Marketing Skills */
(function () {
+ 'use strict';
if (window.__ctDetectCalendly) return;
window.__ctDetectCalendly = true;
window.dataLayer = window.dataLayer || [];
- var ORIGIN_PATTERN = /(^|\.)calendly\.com$/;
+ // The CSS selector matches only Calendly's documented exact embed host.
+ // Do not read iframe.src or its `src` attribute: prefill parameters can
+ // contain invitee PII. The selector engine performs the prefix match without
+ // exposing the URL value to this listener.
+ var CALENDLY_FRAME_SELECTOR = 'iframe[src^=\"https://calendly.com/\"]';
+ var CALENDLY_ORIGIN = 'https://calendly.com';
+ var API_HOSTS = { 'api.calendly.com': true, 'calendly.com': true };
+ var trackedFrames = [];
+ var seenPairs = [];
- function fireConversion(eventUri, inviteeUri) {
- window.dataLayer.push({
- event: 'calendly_event_scheduled',
- event_uri: eventUri || '',
- invitee_uri: inviteeUri || ''
- });
+ function trackFrame(frame) {
+ if (!frame || !frame.contentWindow) return;
+ for (var i = 0; i < trackedFrames.length; i++) {
+ if (trackedFrames[i].frame === frame) {
+ trackedFrames[i].source = frame.contentWindow;
+ trackedFrames[i].origin = CALENDLY_ORIGIN;
+ return;
+ }
+ }
+ trackedFrames.push({ frame: frame, source: frame.contentWindow, origin: CALENDLY_ORIGIN });
+ }
+
+ function scan(root) {
+ if (!root || typeof root.querySelectorAll !== 'function') return;
+ var frames;
+ try { frames = root.querySelectorAll(CALENDLY_FRAME_SELECTOR); } catch (e) { return; }
+ for (var i = 0; i < frames.length; i++) trackFrame(frames[i]);
}
- function looksLikeCalendlyScheduled(data) {
- if (!data || typeof data !== 'object') return false;
- return data.event === 'calendly.event_scheduled';
+ function sourceIsTracked(event) {
+ for (var i = 0; i < trackedFrames.length; i++) {
+ var item = trackedFrames[i];
+ try {
+ if (item.frame.isConnected === true && item.frame.contentWindow === event.source && item.source === event.source && item.origin === event.origin) return true;
+ } catch (e) { /* replaced or inaccessible frames fail closed */ }
+ }
+ return false;
}
- function onMessage(event) {
- if (!event || !event.source) return;
- if (event.source === window) return;
- if (!event.origin || typeof event.origin !== 'string') return;
+ function resourceIdentity(value, kind) {
+ if (typeof value !== 'string' || /[?#]/.test(value)) return null;
+ try {
+ var url = new URL(value);
+ if (url.protocol !== 'https:' || url.port || !API_HOSTS[url.hostname]) return null;
+ var eventMatch = /(?:^|\/)scheduled_events\/([A-Za-z0-9_-]{1,128})\/?$/.exec(url.pathname);
+ var inviteeMatch = /(?:^|\/)scheduled_events\/([A-Za-z0-9_-]{1,128})\/invitees\/([A-Za-z0-9_-]{1,128})\/?$/.exec(url.pathname);
+ if (kind === 'event' && eventMatch) return { eventId: eventMatch[1].toLowerCase() };
+ if (kind === 'invitee' && inviteeMatch) return { eventId: inviteeMatch[1].toLowerCase(), inviteeId: inviteeMatch[2].toLowerCase() };
+ } catch (e) { return null; }
+ return null;
+ }
- var hostMatch = /^https:\/\/([^/]+)$/.exec(event.origin);
- if (!hostMatch) return;
- if (!ORIGIN_PATTERN.test(hostMatch[1])) return;
+ function pairSeen(eventId, inviteeId) {
+ var key = eventId + ':' + inviteeId;
+ for (var i = 0; i < seenPairs.length; i++) if (seenPairs[i] === key) return true;
+ seenPairs.push(key);
+ return false;
+ }
- var data = event.data;
+ function onMessage(message) {
+ if (!message || !message.source || message.source === window || !sourceIsTracked(message)) return;
+ var data = message.data;
if (typeof data === 'string') {
try { data = JSON.parse(data); } catch (e) { return; }
}
- if (!looksLikeCalendlyScheduled(data)) return;
-
+ if (!data || typeof data !== 'object' || data.event !== 'calendly.event_scheduled') return;
var payload = data.payload || {};
- var inviteeUri = payload.invitee && payload.invitee.uri;
var eventUri = payload.event && payload.event.uri;
- if (!inviteeUri || !eventUri) return;
+ var inviteeUri = payload.invitee && payload.invitee.uri;
+ var eventIdentity = resourceIdentity(eventUri, 'event');
+ var inviteeIdentity = resourceIdentity(inviteeUri, 'invitee');
+ if (!eventIdentity || !inviteeIdentity || eventIdentity.eventId !== inviteeIdentity.eventId) return;
+ if (pairSeen(eventIdentity.eventId, inviteeIdentity.inviteeId)) return;
+ window.dataLayer.push({ event: 'calendly_event_scheduled', event_uri: eventUri, invitee_uri: inviteeUri });
+ }
- fireConversion(eventUri, inviteeUri);
+ function start() {
+ if (typeof document === 'undefined') return;
+ scan(document);
+ if (typeof MutationObserver === 'undefined' || !document.documentElement) return;
+ try {
+ var observer = new MutationObserver(function (mutations) {
+ for (var i = 0; i < mutations.length; i++) {
+ var added = mutations[i].addedNodes || [];
+ for (var j = 0; j < added.length; j++) {
+ var node = added[j];
+ if (node && node.tagName === 'IFRAME') scan(document);
+ else scan(node);
+ }
+ if (mutations[i].type === 'attributes' && mutations[i].attributeName === 'src') scan(document);
+ }
+ });
+ observer.observe(document.documentElement, { childList: true, subtree: true, attributes: true, attributeFilter: ['src'] });
+ } catch (e) {}
}
+ if (typeof document !== 'undefined') {
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start, false);
+ else start();
+ }
window.addEventListener('message', onMessage, false);
})();
diff --git a/skills/conversion-tracking/assets/snippets/contact-form-7.js b/skills/conversion-tracking/assets/snippets/contact-form-7.js
index 8831f7b..c743e2c 100644
--- a/skills/conversion-tracking/assets/snippets/contact-form-7.js
+++ b/skills/conversion-tracking/assets/snippets/contact-form-7.js
@@ -2,45 +2,98 @@
* Detects: form submission. Pushes dataLayer event: contact_form_7_submitted
* From the conversion-tracking skill in Marketing Skills */
(function () {
- if (window.__ctDetectContactForm7) return;
+ 'use strict';
+
+ // One shared runtime owns eligibility, accepted event identity, and the ID-only fallback.
+ // A legacy recipe guard without this runtime is unknown code, so do not stack a new listener.
+ var runtime = window.__ctCf7Runtime;
+ if (runtime && runtime.installed) return;
+ if (!runtime && window.__ctDetectContactForm7) return;
+ runtime = runtime || { installed: false };
+ window.__ctCf7Runtime = runtime;
window.__ctDetectContactForm7 = true;
window.dataLayer = window.dataLayer || [];
+ var seenEvents = typeof WeakSet === 'function' ? new WeakSet() : null;
+ var seenEventFallback = [];
- function fireConversion(formEl) {
- // Modern Contact Form 7 (verified against 6.1.6 on a live site) puts
- // data-wpcf7-id on the WRAPPING <div class="wpcf7">, not on the <form>
- // element itself. Check the form first (older/other CF7 setups may
- // still stamp it there) and fall back to the wrapper.
- var formId = '';
+ function isContactForm7Form(formEl) {
+ if (!formEl || (formEl.tagName || '').toLowerCase() !== 'form') return false;
try {
- if (formEl && formEl.getAttribute) {
- formId = formEl.getAttribute('data-wpcf7-id') || '';
- }
- if (!formId && formEl && formEl.closest) {
- var wrap = formEl.closest('.wpcf7');
- if (wrap && wrap.getAttribute) {
- formId = wrap.getAttribute('data-wpcf7-id') || '';
- }
- }
+ if (formEl.classList && formEl.classList.contains('wpcf7-form')) return true;
+ return !!(formEl.closest && formEl.closest('.wpcf7'));
+ } catch (e) {
+ return false;
+ }
+ }
+
+ function validFormId(value) {
+ if (typeof value === 'number' && Number.isFinite(value) && Math.floor(value) === value && value > 0 && value <= 9007199254740991) return String(value);
+ if (typeof value !== 'string' || !/^[1-9]\d*$/.test(value)) return '';
+ var number = Number(value);
+ return Number.isFinite(number) && number <= 9007199254740991 && String(number) === value ? value : '';
+ }
+
+ function readFormId(formEl, event) {
+ // CF7 6.1.6's event detail has contactFormId; read no other detail keys.
+ var detailId = '';
+ try {
+ detailId = validFormId(event && event.detail && event.detail.contactFormId);
+ } catch (e) {}
+ if (detailId) return detailId;
+
+ // Compatibility fallback for markup where the event detail omits the ID.
+ try {
+ var directId = validFormId(formEl.getAttribute && formEl.getAttribute('data-wpcf7-id'));
+ if (directId) return directId;
+ var wrap = formEl.closest && formEl.closest('.wpcf7');
+ return validFormId(wrap && wrap.getAttribute && wrap.getAttribute('data-wpcf7-id'));
} catch (e) {
- // .closest unsupported in very old browsers — non-fatal, form_id stays ''
+ return '';
}
- window.dataLayer.push({
- event: 'contact_form_7_submitted',
- form_id: formId
- });
}
- // Fire path — Contact Form 7's own native DOM CustomEvent, dispatched on
- // the <form> element once an AJAX submission passes CF7's server-side
- // validation and spam checks, then bubbles to document. This is the ONLY
- // path this recipe tracks; a legacy non-AJAX (full page reload) CF7 setup
- // never dispatches this event at all — CF7 itself provides no client-side
- // success signal in that mode either (the real module only logs a
- // warning for it, it never fires a conversion).
+ // CF7 can send both clicks while the first request is still pending.
+ // Group those requests without blocking or changing the form submission.
+ document.addEventListener('wpcf7beforesubmit', function (event) {
+ var formEl = event && event.target;
+ if (!isContactForm7Form(formEl)) return;
+ if (!formEl.__ctCf7Attempt || formEl.getAttribute('data-status') !== 'submitting') {
+ formEl.__ctCf7Attempt = { emitted: false };
+ }
+ }, false);
+
document.addEventListener('wpcf7mailsent', function (event) {
var formEl = event && event.target;
- if (!formEl || (formEl.tagName || '').toLowerCase() !== 'form') return;
- fireConversion(formEl);
+ if (!isContactForm7Form(formEl)) return;
+ if (seenEvents) {
+ if (seenEvents.has(event)) return;
+ seenEvents.add(event);
+ } else {
+ if (seenEventFallback.indexOf(event) !== -1) return;
+ seenEventFallback.push(event);
+ if (seenEventFallback.length > 50) seenEventFallback.shift();
+ }
+
+ var formId = readFormId(formEl, event);
+ if (!formId) return;
+ var attempt = formEl.__ctCf7Attempt;
+ if (attempt && attempt.emitted) return;
+ if (attempt) attempt.emitted = true;
+
+ // The optional Method 2 adapter may enrich this accepted event. It must
+ // return literal true only after pushing; otherwise the shared core emits
+ // the same event with IDs only. Neither path inspects event.detail values.
+ var enriched = false;
+ try {
+ if (typeof window.__ctCf7Method2Emit === 'function') {
+ enriched = window.__ctCf7Method2Emit(formEl, event, formId) === true;
+ }
+ } catch (e) {
+ enriched = false;
+ }
+ if (!enriched) {
+ window.dataLayer.push({ event: 'contact_form_7_submitted', form_id: formId });
+ }
}, false);
+ runtime.installed = true;
})();
diff --git a/skills/conversion-tracking/assets/snippets/divi-forms.js b/skills/conversion-tracking/assets/snippets/divi-forms.js
index 0873fa0..27e3a27 100644
--- a/skills/conversion-tracking/assets/snippets/divi-forms.js
+++ b/skills/conversion-tracking/assets/snippets/divi-forms.js
@@ -5,98 +5,48 @@
if (window.__ctDetectDiviForms) return;
window.__ctDetectDiviForms = true;
window.dataLayer = window.dataLayer || [];
-
- // Real id if the container has one, else a synthetic per-page-load key
- // stamped onto it — ported directly from the production module's
- // getFormKey helper, so multiple Divi forms on one page stay distinct.
- var keyCounter = 0;
-
- function getFormKey(container) {
- if (!container) return '';
- if (container.id) return container.id;
- var key = container.getAttribute('data-ct-key');
- if (!key) {
- keyCounter++;
- key = 'divi-' + keyCounter;
- container.setAttribute('data-ct-key', key);
- }
- return key;
- }
-
- function fireConversion(formId) {
- window.dataLayer.push({
- event: 'divi_form_submitted',
- form_id: formId || ''
- });
- }
-
- // Divi renders BOTH validation errors and the success notice into
- // .et-pb-contact-message — the element itself carries no success/error
- // marker. Errors mark the offending inputs with .et_contact_error and
- // wrap the message text in .et_pb_contact_error_text. Only fire when
- // the message has text and no error markers are present.
- function maybeReportSuccess(container) {
+ var reported = typeof WeakSet === 'function' ? new WeakSet() : null;
+ function inspect(container) {
if (!container || !container.querySelector) return;
-
- var msg = container.querySelector('.et-pb-contact-message');
- if (!msg) return;
-
- var text = (msg.textContent || '').trim();
- if (!text) return;
-
+ var notice;
try {
- if (msg.querySelector('.et_pb_contact_error_text')) return;
- if (container.querySelector('.et_contact_error')) return;
- } catch (e) {
- // Can't tell success from error — do not fire
- return;
- }
-
- // Permanent stamp: long-tail mutations of the container (other
- // plugins, widgets) must not re-report a message that already fired
- if (msg.getAttribute('data-ct-reported') === 'true') return;
- msg.setAttribute('data-ct-reported', 'true');
-
- fireConversion(getFormKey(container));
+ notice = container.querySelector('.et-pb-contact-message.et_pb_success_message');
+ if (!notice || container.querySelector('form.et_pb_contact_form') ||
+ container.querySelector('.et_pb_contact_error_meesage') ||
+ container.querySelector('.et_contact_error')) return;
+ } catch (e) { return; }
+ if (reported && reported.has(notice)) return;
+ if (reported) reported.add(notice);
+ var id = container.id || (container.getAttribute && container.getAttribute('data-id')) || '';
+ if (!id) return;
+ var adapter = window.__ctDiviMethod2Emit;
+ if (typeof adapter === 'function' && adapter(container, String(id)) === true) return;
+ window.dataLayer.push({ event: 'divi_form_submitted', form_id: String(id) });
}
-
- function observeContainer(container) {
- if (typeof MutationObserver === 'undefined') return;
- if (!container || !container.getAttribute) return;
- if (container.getAttribute('data-ct-observed') === 'true') return;
- container.setAttribute('data-ct-observed', 'true');
-
- var observer = new MutationObserver(function () {
- maybeReportSuccess(container);
- });
-
- observer.observe(container, {
- childList: true,
- subtree: true,
- characterData: true
- });
+ function observe(container) {
+ if (!container || container.__ctDiviObserved || typeof MutationObserver === 'undefined') return;
+ container.__ctDiviObserved = true;
+ new MutationObserver(function () { inspect(container); }).observe(container,
+ { childList: true, subtree: true, attributes: true, attributeFilter: ['class'] });
+ inspect(container);
}
-
- function startMutationObserver() {
- if (typeof MutationObserver === 'undefined') return;
-
- var containers = document.querySelectorAll('.et_pb_contact_form_container');
- for (var c = 0; c < containers.length; c++) {
- observeContainer(containers[c]);
+ function start() {
+ var existing = document.querySelectorAll('.et_pb_contact_form_container');
+ for (var i = 0; i < existing.length; i++) observe(existing[i]);
+ if (typeof MutationObserver !== 'undefined' && document.documentElement) {
+ new MutationObserver(function (records) {
+ for (var r = 0; r < records.length; r++) {
+ for (var n = 0; n < records[r].addedNodes.length; n++) {
+ var node = records[r].addedNodes[n];
+ if (node.nodeType !== 1) continue;
+ if (node.matches && node.matches('.et_pb_contact_form_container')) observe(node);
+ var nested = node.querySelectorAll ? node.querySelectorAll('.et_pb_contact_form_container') : [];
+ for (var j = 0; j < nested.length; j++) observe(nested[j]);
+ }
+ }
+ }).observe(document.documentElement, { childList: true, subtree: true });
}
}
-
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', function () {
- startMutationObserver();
- });
- } else {
- startMutationObserver();
- }
-
- // Also rescan after window load in case Divi loads forms late
- // (observeContainer is idempotent per container)
- window.addEventListener('load', function () {
- startMutationObserver();
- });
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start, { once: true });
+ else start();
})();
diff --git a/skills/conversion-tracking/assets/snippets/elementor-forms.js b/skills/conversion-tracking/assets/snippets/elementor-forms.js
index 9e30aa4..fe413b7 100644
--- a/skills/conversion-tracking/assets/snippets/elementor-forms.js
+++ b/skills/conversion-tracking/assets/snippets/elementor-forms.js
@@ -5,107 +5,48 @@
if (window.__ctDetectElementorForms) return;
window.__ctDetectElementorForms = true;
window.dataLayer = window.dataLayer || [];
-
- // Best-effort, non-PII identifier: the form's own id/name, or the
- // nearest ancestor carrying Elementor's standard data-id widget-instance
- // attribute. Never reads field values.
- function bestEffortFormId(formEl) {
- if (!formEl) return '';
- if (formEl.id) return formEl.id;
- var name = formEl.getAttribute && formEl.getAttribute('name');
- if (name) return name;
+ var seenEvents = typeof WeakSet === 'function' ? new WeakSet() : null;
+ function formFrom(target) {
try {
- var withId = formEl.closest && formEl.closest('[data-id]');
- if (withId) return withId.getAttribute('data-id') || '';
- } catch (e) {
- // .closest not available — non-fatal
- }
- return '';
+ if (!target || target === document || target === window) return null;
+ if (target.matches && target.matches('form.elementor-form')) return target;
+ return target.closest ? target.closest('form.elementor-form') : null;
+ } catch (e) { return null; }
}
-
- function fireConversion(formId) {
- window.dataLayer.push({
- event: 'elementor_form_submitted',
- form_id: formId || ''
- });
+ function formId(form) {
+ if (!form) return '';
+ if (form.id) return form.id;
+ var name = form.getAttribute && form.getAttribute('name');
+ if (name && name !== 'New Form') return name;
+ var widget = form.closest && form.closest('[data-id]');
+ return widget && widget.getAttribute('data-id') || '';
}
-
- // Same form-resolution chain the production module uses (event.target
- // -> most recently clicked Elementor submit button's form -> the sole
- // .elementor-form on the page) — ported here so the recipe can attach a
- // real form_id instead of firing event-only.
- var lastClickedForm = null;
-
- function trackClick(event) {
- try {
- var target = event.target;
- if (!target || !target.closest) return;
- var form = target.closest('form.elementor-form');
- if (form) lastClickedForm = form;
- } catch (e) {
- // non-fatal
+ function onSuccess(event) {
+ if (event && seenEvents) {
+ if (seenEvents.has(event)) return;
+ seenEvents.add(event);
}
- }
-
- function resolveFormFromTarget(target) {
- if (!target || target === document || target === window) return null;
- try {
- if ((target.tagName || '').toLowerCase() === 'form' &&
- target.classList && target.classList.contains('elementor-form')) {
- return target;
- }
- if (target.closest) {
- var parentForm = target.closest('form.elementor-form');
- if (parentForm) return parentForm;
- }
- } catch (e) {
- // non-fatal
+ var form = formFrom(event && event.target);
+ var id = formId(form);
+ if (!form || !id) return;
+ var adapter = window.__ctElementorMethod2Emit;
+ if (typeof adapter === 'function') {
+ try { if (adapter(form, id) === true) return; }
+ catch (e) { return; }
}
- return null;
+ window.dataLayer.push({ event: 'elementor_form_submitted', form_id: String(id) });
}
-
- // Fire path — Elementor Pro's own jQuery event, triggered on `document`
- // once an AJAX submission passes server-side validation. This is the ONLY
- // path this recipe tracks; Elementor Pro forms submit exclusively via
- // Elementor's own AJAX pipeline, so there is no non-AJAX mode to miss.
- var successHooked = false;
-
- function hookElementorSuccess() {
- if (successHooked) return true;
- // A bare $ is only trusted when it looks like jQuery ($.fn exists), so
- // another library that claims $ cannot break the hook.
- var jQ = null;
- if (typeof jQuery !== 'undefined') jQ = jQuery;
- else if (typeof $ !== 'undefined' && typeof $.fn !== 'undefined') jQ = $;
- if (!jQ) return false;
- jQ(document).on('submit_success', function (event) {
- var formEl = resolveFormFromTarget(event && event.target);
- if (!formEl && lastClickedForm) formEl = lastClickedForm;
- lastClickedForm = null;
-
- if (!formEl) {
- try {
- var forms = document.querySelectorAll('.elementor-form');
- if (forms.length === 1) formEl = forms[0];
- } catch (e) {
- // non-fatal
- }
- }
-
- fireConversion(bestEffortFormId(formEl));
- });
- successHooked = true;
+ var handlerBound = false;
+ function hook() {
+ if (handlerBound) return true;
+ var jq = typeof jQuery !== 'undefined' ? jQuery : (typeof $ !== 'undefined' ? $ : null);
+ if (!jq) return false;
+ jq(document).on('submit_success', onSuccess);
+ handlerBound = true;
return true;
}
-
- document.addEventListener('click', trackClick, true);
-
- if (!hookElementorSuccess()) {
- document.addEventListener('DOMContentLoaded', function () {
- hookElementorSuccess();
- });
- window.addEventListener('load', function () {
- hookElementorSuccess();
- });
+ if (!hook()) {
+ document.addEventListener('DOMContentLoaded', hook, { once: true });
+ window.addEventListener('load', hook, { once: true });
}
})();
diff --git a/skills/conversion-tracking/assets/snippets/fluent-forms.js b/skills/conversion-tracking/assets/snippets/fluent-forms.js
index 6e7aa41..3dd920d 100644
--- a/skills/conversion-tracking/assets/snippets/fluent-forms.js
+++ b/skills/conversion-tracking/assets/snippets/fluent-forms.js
@@ -2,142 +2,100 @@
* Detects: form submission. Pushes dataLayer event: fluent_forms_submitted
* From the conversion-tracking skill in Marketing Skills */
(function () {
- if (window.__ctDetectFluentForms) return;
- window.__ctDetectFluentForms = true;
+ if (window.__ctFluentForms) return;
+ window.__ctFluentForms = true;
window.dataLayer = window.dataLayer || [];
-
- function isFluentForm(formEl) {
- if (!formEl) return false;
- if (formEl.className && formEl.className.indexOf('frm-fluent-form') !== -1) return true;
+ var listeners = [], lastEvent = null;
+ // Fluent Forms 6.2.5 reports one success response through three different
+ // event objects. Deduplicate by response-object identity and original form
+ // node; never inspect or retain a response's fields.
+ var seenResponses = typeof WeakMap === 'function' ? new WeakMap() : null;
+ window.__ctFluentSubscribe = function (listener) {
+ if (listener && typeof listener === 'object') listeners.push(listener);
+ };
+ function isForm(form) {
try {
- if (formEl.closest && formEl.closest('.fluentform')) return true;
- } catch (e) {
- // .closest not available — fall back to ID check
+ if (!form || String(form.tagName || '').toLowerCase() !== 'form') return false;
+ if (String(form.className || '').indexOf('frm-fluent-form') !== -1) return true;
+ if (form.closest && form.closest('.fluentform')) return true;
+ return /^fluentform_\d+$/.test(form.id || '');
+ } catch (e) { return false; }
+ }
+ function asForm(candidate) {
+ try {
+ var el = candidate;
+ if (el && el.jquery && el.length) el = el[0];
+ return isForm(el) ? el : null;
+ } catch (e) { return null; }
+ }
+ function notify(phase, form, candidate, event, arg2, arg3) {
+ var handled = false;
+ for (var i=0;i<listeners.length;i++) {
+ try { var fn=listeners[i] && listeners[i][phase]; if(typeof fn==='function' && fn(form,candidate,event,arg2,arg3)===true)handled=true; } catch(e) {}
}
- var id = formEl.id || '';
- return /^fluentform_\d+$/.test(id);
+ return handled;
}
-
- // Accepts a jQuery object or a DOM element; returns the underlying DOM
- // element if it is a Fluent Forms <form>, else null.
- function asFluentForm(candidate) {
- if (!candidate) return null;
- var el = candidate;
- if (el.jquery && el.length) el = el[0]; // unwrap jQuery objects only —
- // never plain elements: form[0] on a raw <form> is its first control.
- if ((el.tagName || '').toLowerCase() === 'form' && isFluentForm(el)) return el;
- return null;
+ function submit(event) {
+ try { var form=event.target; if(isForm(form)) notify('beforeAttempt',form,false,event); } catch(e) {}
}
-
- // Click-tracking fallback for form attribution: remember the Fluent form
- // whose submit button was most recently clicked, in case an old Fluent
- // Forms version fires the success event without a form reference.
- var lastActiveForm = null;
-
- function trackSubmitClick(event) {
+ function resolve(event,arg2,arg3) {
try {
- var target = event.target;
- if (!target || !target.closest) return;
- var btn = target.closest('.ff-btn-submit');
- if (!btn) return;
- var form = btn.closest('form');
- if (form && isFluentForm(form)) lastActiveForm = form;
- } catch (e) {
- // non-fatal
- }
+ var form=asForm(arg2 && arg2.form) || asForm(arg3) || asForm(arg2);
+ if(form)return form;
+ var oe=event && event.originalEvent;
+ if(oe && oe.detail) return asForm(oe.detail.form);
+ return asForm(event && event.target);
+ } catch(e) { return null; }
}
-
- // Resolution order (first valid Fluent form wins) — live-verified against
- // Fluent Forms 6.2.5, 2026-07-05:
- // 1. data.form from the handler's data argument — the <body> dispatch
- // passes { form, config, response } where form is the jQuery-wrapped
- // form (also accept data itself being the form, defensively)
- // 2. event.originalEvent.detail.form — the native CustomEvent dispatch
- // carries the raw form element in detail
- // 3. event.target, if it IS a Fluent form (direct-on-form re-trigger)
- // 4. the form whose submit button was most recently clicked
- // 5. the only .frm-fluent-form on the page, if exactly one exists
- function resolveSuccessForm(event, data) {
- var el = asFluentForm(data && data.form) || asFluentForm(data);
- if (el) return el;
-
+ function responseFor(event, arg2) {
try {
- var oe = event && event.originalEvent;
- if (oe && oe.detail) {
- el = asFluentForm(oe.detail.form);
- if (el) return el;
- }
- } catch (e) {
- // originalEvent/detail unreadable — keep falling back
- }
-
- el = asFluentForm(event && event.target);
- if (el) return el;
-
- if (lastActiveForm && document.contains(lastActiveForm) && isFluentForm(lastActiveForm)) {
- return lastActiveForm;
- }
-
+ var descriptor = arg2 && Object.getOwnPropertyDescriptor(arg2, 'response');
+ var response = descriptor && Object.prototype.hasOwnProperty.call(descriptor, 'value') ? descriptor.value : null;
+ if (response && typeof response === 'object') return response;
+ var originalEvent = event && event.originalEvent;
+ var detail = originalEvent && originalEvent.detail;
+ descriptor = detail && Object.getOwnPropertyDescriptor(detail, 'response');
+ response = descriptor && Object.prototype.hasOwnProperty.call(descriptor, 'value') ? descriptor.value : null;
+ return response && typeof response === 'object' ? response : null;
+ } catch(e) { return null; }
+ }
+ function alreadySeen(response, form) {
try {
- var forms = document.querySelectorAll('.frm-fluent-form');
- if (forms.length === 1) return forms[0];
- } catch (e) {
- // querySelectorAll unavailable — give up
- }
-
- return null;
+ if (!seenResponses || !response || !form || typeof response !== 'object' || typeof form !== 'object') return true;
+ var forms = seenResponses.get(response);
+ if (!forms) {
+ forms = typeof WeakSet === 'function' ? new WeakSet() : null;
+ if (!forms) return true;
+ seenResponses.set(response, forms);
+ }
+ if (forms.has(form)) return true;
+ forms.add(form);
+ return false;
+ } catch(e) { return true; }
}
-
- // Dedup: one successful submission reaches a document-level jQuery
- // listener TWICE on current Fluent Forms (the jQuery <body> trigger and
- // the native CustomEvent) — verified live. Both duplicates resolve to the
- // same form within the same tick, so fire once per form per 2s window
- // (matches production listener behaviour). Rapid legitimate
- // re-submissions of the same form take well over 2s (server round trip +
- // success render), so none are lost.
- var lastFiredForm = null;
- var lastFiredAt = 0;
-
- function fireConversion(formEl) {
- var now = new Date().getTime();
- if (lastFiredForm === formEl && now - lastFiredAt < 2000) return;
- lastFiredForm = formEl;
- lastFiredAt = now;
- window.dataLayer.push({
- event: 'fluent_forms_submitted',
- form_id: (formEl && formEl.id) || ''
- });
+ function success(event,arg2,arg3) {
+ try {
+ if (event && typeof event === 'object' && event === lastEvent) return;
+ lastEvent=event;
+ if (event && typeof event === 'object') setTimeout(function(){if(lastEvent===event)lastEvent=null;},0);
+ var form=resolve(event,arg2,arg3);
+ if(!form)return;
+ var response=responseFor(event,arg2);
+ if(!response || alreadySeen(response,form))return;
+ if(!notify('onCandidate',form,true,event,arg2,arg3)) window.dataLayer.push({event:'fluent_forms_submitted',form_id:form.id || ''});
+ } catch(e) {}
}
-
- // Fire path — Fluent Forms' success signal, fired once an AJAX submission
- // passes server-side validation. This is the ONLY path this recipe
- // tracks; Fluent Forms always submits via AJAX (there is no non-AJAX
- // mode to miss). Client-side validation failures, native HTML5 blocks,
- // and server-side rejections never fire it. Hooked via jQuery because
- // the <body> dispatch is jQuery-only AND jQuery is guaranteed on any
- // working Fluent Forms page (Fluent Forms' own submission handler
- // requires it — without jQuery the form cannot submit at all).
- var successHooked = false;
-
- function hookFluentSuccess() {
- if (successHooked) return true;
- if (typeof window.jQuery === 'undefined') return false;
-
- window.jQuery(document).on('fluentform_submission_success', function (event, data) {
- fireConversion(resolveSuccessForm(event, data));
- });
- successHooked = true;
- return true;
+ document.addEventListener('submit',submit,true);
+ function hook() {
+ try {
+ if (window.__ctFluentSuccessHooked || !window.jQuery) return false;
+ window.__ctFluentSuccessHooked=true;
+ window.jQuery(document).on('fluentform_submission_success',success);
+ return true;
+ } catch(e) { return false; }
}
-
- document.addEventListener('click', trackSubmitClick, true);
-
- if (!hookFluentSuccess()) {
- document.addEventListener('DOMContentLoaded', function () {
- hookFluentSuccess();
- });
- window.addEventListener('load', function () {
- hookFluentSuccess();
- });
+ if(!hook()) {
+ document.addEventListener('DOMContentLoaded',hook);
+ window.addEventListener('load',hook);
}
})();
diff --git a/skills/conversion-tracking/assets/snippets/formidable-forms.js b/skills/conversion-tracking/assets/snippets/formidable-forms.js
index 12bafa9..5fe7629 100644
--- a/skills/conversion-tracking/assets/snippets/formidable-forms.js
+++ b/skills/conversion-tracking/assets/snippets/formidable-forms.js
@@ -2,316 +2,200 @@
* Detects: form submission. Pushes dataLayer event: formidable_forms_submitted
* From the conversion-tracking skill in Marketing Skills */
(function () {
+ 'use strict';
+
+ // Shared with the recipe snippet so template + recipe installation is one listener.
if (window.__ctDetectFormidableForms) return;
window.__ctDetectFormidableForms = true;
+ if (!/^https?:$/.test(window.location.protocol)) return;
window.dataLayer = window.dataLayer || [];
- var SUCCESS_WINDOW_MS = 10000;
- var DEFERRED_MARKER_KEY = '__ctDetectFormidableNativePending';
- var DEFERRED_MARKER_TTL_MS = 60000;
-
- function isFormidableForm(formEl) {
- if (!formEl) return false;
- try {
- if (formEl.closest && formEl.closest('.frm_forms')) return true;
- } catch (e) {
- // .closest not available — fall back to class check
- }
- var cls = ' ' + (formEl.className || '') + ' ';
- return cls.indexOf(' frm-show-form ') !== -1;
- }
+ var MARKER_KEY = '__ctDetectFormidableNativePendingV2';
+ var MARKER_TTL_MS = 60000;
+ var handledResponses = typeof WeakSet === 'function' ? new WeakSet() : [];
+ var activeAttempts = [];
+ var jqueryHooked = false;
- function fireConversion(formId, formEl) {
- // Both AJAX events (and the native path) can resolve to the same
- // submission — dedupe with a short-lived flag on the form when it's
- // resolvable. If it isn't resolvable we still fire (favors counting a
- // real submission over silently dropping it).
- if (!formEl && formId) formEl = document.getElementById('form_' + formId);
- if (formEl) {
- if (formEl.getAttribute('data-ct-processing') === 'true') return;
- formEl.setAttribute('data-ct-processing', 'true');
- setTimeout(function () { formEl.removeAttribute('data-ct-processing'); }, 2000);
- disarmWatcher(formEl);
- }
- window.dataLayer.push({
- event: 'formidable_forms_submitted',
- form_id: formId || ''
- });
+ function safeId(value) {
+ var id = String(value || '');
+ return /^[1-9][0-9]*$/.test(id) ? id : '';
}
- // ---- Shared validation-marker check (used by both fire paths) ----
-
- function isNodeHidden(el) {
+ // Formidable's hidden form_id is non-sensitive structural metadata. No other
+ // field value, response property, label, HTML, or rendered text is inspected.
+ function formId(form) {
+ if (!form || typeof form.querySelector !== 'function') return '';
try {
- if (el.hidden) return true;
- if (el.getAttribute && el.getAttribute('aria-hidden') === 'true') return true;
- var view = el.ownerDocument && el.ownerDocument.defaultView;
- if (view && view.getComputedStyle) {
- var cs = view.getComputedStyle(el);
- if (cs && (cs.display === 'none' || cs.visibility === 'hidden')) return true;
- }
+ var input = form.querySelector('input[name="form_id"]');
+ return input && input.getAttribute ? safeId(input.getAttribute('value')) : '';
} catch (e) {
- // fall through
+ return '';
}
- return false;
}
- // Formidable's standard error markers: .frm_error (per-field message),
- // .frm_error_style (form-level rejection box), .frm_blank_field (state
- // class on a required-but-blank field), [aria-invalid="true"].
- function hasVisibleValidationErrors(scopeEl) {
- if (!scopeEl || !scopeEl.querySelectorAll) return false;
- try {
- var nodes = scopeEl.querySelectorAll(
- '.frm_error, .frm_error_style, .frm_blank_field, [aria-invalid="true"]'
- );
- for (var i = 0; i < nodes.length; i++) {
- var node = nodes[i];
- if (isNodeHidden(node)) continue;
- if (node.getAttribute && node.getAttribute('aria-invalid') === 'true') return true;
- var cls = ' ' + (typeof node.className === 'string' ? node.className : '') + ' ';
- if (cls.indexOf(' frm_blank_field ') !== -1) return true;
- if ((node.textContent || '').trim()) return true;
- }
- } catch (e) {
- // fall through
- }
- return false;
+ function wrapperFor(id) {
+ if (!id) return null;
+ try { return document.getElementById('frm_form_' + id + '_container'); } catch (e) { return null; }
}
- function hasServerRejectionMarkers() {
- try {
- var wrappers = document.querySelectorAll('.frm_forms');
- for (var i = 0; i < wrappers.length; i++) {
- if (hasVisibleValidationErrors(wrappers[i])) return true;
- }
- } catch (e) {
- // fall through
- }
- return false;
+ function hasNode(scope, selector) {
+ if (!scope || typeof scope.querySelector !== 'function') return false;
+ try { return !!scope.querySelector(selector); } catch (e) { return false; }
}
- function hasSuccessMessage() {
- try {
- var nodes = document.querySelectorAll('.frm_message');
- for (var i = 0; i < nodes.length; i++) {
- if (isNodeHidden(nodes[i])) continue;
- if ((nodes[i].textContent || '').trim()) return true;
- }
- } catch (e) {
- // fall through
- }
- return false;
+ function hasRejectionMarker(id) {
+ return hasNode(wrapperFor(id), '.frm_error, .frm_error_style, .frm_blank_field, [aria-invalid="true"]');
}
- // ---- Fire path 1: AJAX success events ----
-
- var activeWatchers = [];
+ function hasSuccessMarker(id) {
+ return hasNode(wrapperFor(id), '.frm_message');
+ }
- function findWatcher(formEl) {
- for (var w = 0; w < activeWatchers.length; w++) {
- if (activeWatchers[w].form === formEl) return activeWatchers[w];
+ function responseWasHandled(response) {
+ if (!response || (typeof response !== 'object' && typeof response !== 'function')) return true;
+ if (typeof WeakSet === 'function' && handledResponses instanceof WeakSet) {
+ if (handledResponses.has(response)) return true;
+ handledResponses.add(response);
+ return false;
}
- return null;
+ for (var i = 0; i < handledResponses.length; i++) {
+ if (handledResponses[i] === response) return true;
+ }
+ handledResponses.push(response);
+ if (handledResponses.length > 100) handledResponses.shift();
+ return false;
}
- function disarmWatcher(formEl) {
- var existing = findWatcher(formEl);
- if (existing && typeof existing.cleanup === 'function') existing.cleanup();
+ function push(id) {
+ if (!id) return;
+ window.dataLayer.push({ event: 'formidable_forms_submitted', form_id: id });
}
- function handleAjaxSuccessEvent(event) {
- var formId = '';
+ // Optional Method 2 adapter owns any enriched push. The detector passes only
+ // structural metadata and accepts only a literal true handled verdict; it
+ // never receives or inspects an adapter payload.
+ function emitAccepted(id, form, source) {
+ var handled = false;
try {
- if (event.detail && event.detail.frmVars && event.detail.frmVars.formID) {
- formId = event.detail.frmVars.formID;
+ if (typeof window.__ctFormidableMethod2Emit === 'function') {
+ handled = window.__ctFormidableMethod2Emit(id, form, source) === true;
}
- } catch (e) {
- // detail not available
- }
-
- var formEl = formId ? document.getElementById('form_' + formId) : null;
- if (!formEl) {
- // Fallback: the first form inside the first .frm_forms wrapper.
- try {
- var wrappers = document.querySelectorAll('.frm_forms');
- for (var i = 0; i < wrappers.length; i++) {
- var f = wrappers[i].querySelector('form');
- if (f) { formEl = f; break; }
- }
- } catch (e) {
- // querySelectorAll unavailable — give up
- }
- }
-
- fireConversion(formId, formEl);
+ } catch (e) {}
+ if (!handled) push(id);
}
- // ---- Fire path 2: native (non-AJAX) pagehide watcher + deferred verdict ----
+ // In 6.32.1 these are jQuery events: formidable.js calls
+ // jQuery(document).trigger(name, [form, response]). addEventListener does not
+ // receive these success events. The response is used only by object identity
+ // so the redirect and completion callbacks for one response count once.
+ function onAjaxSuccess(event, form, response) {
+ var id = formId(form);
+ if (!id || !response || responseWasHandled(response)) return;
+ emitAccepted(id, form, 'ajax');
+ disarmAttempt(form);
+ }
- function writeDeferredMarker(formId) {
- try {
- window.sessionStorage.setItem(DEFERRED_MARKER_KEY, JSON.stringify({
- t: Date.now(),
- path: window.location.pathname,
- formId: formId
- }));
- return true;
- } catch (e) {
- return false;
- }
+ function hookJquery() {
+ if (jqueryHooked) return true;
+ var jq = window.jQuery || window.$;
+ if (typeof jq !== 'function') return false;
+ jq(document).on(
+ 'frmFormComplete.ctRecipe frmBeforeFormRedirect.ctRecipe',
+ onAjaxSuccess
+ );
+ jqueryHooked = true;
+ return true;
}
- function takeDeferredMarker() {
+ function readMarker() {
try {
- var raw = window.sessionStorage.getItem(DEFERRED_MARKER_KEY);
+ var raw = window.sessionStorage.getItem(MARKER_KEY);
if (!raw) return null;
- window.sessionStorage.removeItem(DEFERRED_MARKER_KEY);
- var data = JSON.parse(raw);
- if (!data || typeof data !== 'object') return null;
- if (!data.t || Date.now() - data.t > DEFERRED_MARKER_TTL_MS) return null;
- return data;
+ window.sessionStorage.removeItem(MARKER_KEY);
+ var marker = JSON.parse(raw);
+ if (!marker || typeof marker !== 'object') return null;
+ if (typeof marker.t !== 'number' || Date.now() < marker.t || Date.now() - marker.t > MARKER_TTL_MS) return null;
+ if (marker.hadSuccessAtSubmit === true) return null;
+ return { id: safeId(marker.id), origin: marker.origin, path: marker.path };
} catch (e) {
- try { window.sessionStorage.removeItem(DEFERRED_MARKER_KEY); } catch (e2) {}
+ try { window.sessionStorage.removeItem(MARKER_KEY); } catch (e2) {}
return null;
}
}
- // Runs once at module init on every page load. Consumes the marker the
- // previous page wrote at pagehide (if any) and reads the verdict from the
- // markup Formidable rendered into THIS page. Rejection is checked first:
- // the rejected-POST re-render always carries error markers, so a missed
- // fire here degrades to under-counting, never fabricating.
- function processDeferredVerdict() {
- var marker = takeDeferredMarker();
- if (!marker) return;
-
- if (hasServerRejectionMarkers()) return;
-
- if (hasSuccessMessage()) {
- fireConversion(marker.formId, null);
- return;
- }
- // No Formidable markup either way. A success configured to redirect
- // lands on a different path with no .frm_message — treat a changed
- // pathname as that redirect. A rejection can't look like this: the
- // rejected POST always re-renders the form WITH error markers.
- if (marker.path && window.location.pathname !== marker.path) {
- fireConversion(marker.formId, null);
+ // Native success either renders a form-specific message or redirects away
+ // from the submitted form. Rejection stays on the form page with errors.
+ // Only origin and pathname are retained, never query strings or form answers.
+ function processNativeMessage() {
+ var marker = readMarker();
+ if (!marker || !marker.id || hasRejectionMarker(marker.id)) return;
+ var redirected = marker.origin === window.location.origin &&
+ typeof marker.path === 'string' && marker.path !== window.location.pathname &&
+ !wrapperFor(marker.id) && !hasNode(document, '.frm_error, .frm_error_style');
+ if (hasSuccessMarker(marker.id) || redirected) {
+ var wrapper = wrapperFor(marker.id);
+ var form = null;
+ try { form = wrapper && wrapper.querySelector ? wrapper.querySelector('form') : null; } catch (e) {}
+ emitAccepted(marker.id, form, 'native');
}
- // Same page, no markers either way — ambiguous, do not fire.
}
- function armNativeWatcher(formEl, formId, pagehideTrusted) {
- var existing = findWatcher(formEl);
- if (existing) {
- existing.refresh(formId, pagehideTrusted);
- return;
+ function getAttempt(form) {
+ for (var i = 0; i < activeAttempts.length; i++) {
+ if (activeAttempts[i].form === form) return activeAttempts[i];
}
+ return null;
+ }
- var entry = { form: formEl, refresh: refresh, cleanup: cleanup };
- activeWatchers.push(entry);
-
- var fired = false;
- var timer = null;
- var pagehideArmed = false;
-
- function onPageHide() {
- if (fired) return;
- // Click-then-leave guard: a visitor blocked by Formidable's own
- // validation who then navigates away must not count.
- if (hasVisibleValidationErrors(formEl)) return;
- fired = true;
- if (formEl.getAttribute('data-ct-processing') !== 'true') {
- writeDeferredMarker(formId);
- }
- cleanup();
- }
+ function disarmAttempt(form) {
+ var attempt = getAttempt(form);
+ if (!attempt) return;
+ try { window.removeEventListener('pagehide', attempt.onPageHide, true); } catch (e) {}
+ var index = activeAttempts.indexOf(attempt);
+ if (index !== -1) activeAttempts.splice(index, 1);
+ }
- function armPagehide() {
- if (pagehideArmed) return;
+ function armNativeMessageAttempt(event) {
+ var form = event && event.target;
+ if (!form || String(form.tagName || '').toLowerCase() !== 'form') return;
+ var isFormidable = false;
+ try { isFormidable = !!(form.closest && form.closest('.frm_forms')); } catch (e) {}
+ if (!isFormidable) return;
+ var id = formId(form);
+ if (!id) return;
+ var wrapper = wrapperFor(id);
+ var hadSuccessAtSubmit = hasNode(wrapper, '.frm_message');
+ var prior = getAttempt(form);
+ if (prior) disarmAttempt(form);
+ var attempt = { form: form, id: id, hadSuccessAtSubmit: hadSuccessAtSubmit, onPageHide: null };
+ attempt.onPageHide = function () {
+ disarmAttempt(form);
+ // Old server errors remain visible while a corrected native POST leaves.
+ // Decide acceptance from the response page, not the departing page.
+ if (attempt.hadSuccessAtSubmit) return;
try {
- window.addEventListener('pagehide', onPageHide, true);
- pagehideArmed = true;
- } catch (e) {
- // fall through
- }
- }
-
- function disarmPagehide() {
- if (!pagehideArmed) return;
- try { window.removeEventListener('pagehide', onPageHide, true); } catch (e) {}
- pagehideArmed = false;
- }
-
- function startTimer() {
- if (timer) clearTimeout(timer);
- timer = setTimeout(function () {
- if (!fired) cleanup();
- }, SUCCESS_WINDOW_MS);
- }
-
- function cleanup() {
- if (timer) { clearTimeout(timer); timer = null; }
- disarmPagehide();
- var idx = activeWatchers.indexOf(entry);
- if (idx !== -1) activeWatchers.splice(idx, 1);
- }
-
- // A later submit on the same form: the visitor corrected a failed
- // field and re-submitted. Refresh everything to the latest attempt.
- function refresh(nextFormId, nextPagehideTrusted) {
- if (fired) return;
- formId = nextFormId;
- if (nextPagehideTrusted) armPagehide();
- else disarmPagehide();
- startTimer();
- }
-
- if (pagehideTrusted) armPagehide();
- startTimer();
+ window.sessionStorage.setItem(MARKER_KEY, JSON.stringify({
+ t: Date.now(),
+ id: attempt.id,
+ hadSuccessAtSubmit: false,
+ origin: window.location.origin,
+ path: window.location.pathname
+ }));
+ } catch (e) {}
+ };
+ activeAttempts.push(attempt);
+ try { window.addEventListener('pagehide', attempt.onPageHide, true); } catch (e) {}
}
- // Bubble-phase submit listener — arms the native watcher on every
- // Formidable submit attempt. This fires even when Formidable
- // preventDefaults it (the event still dispatches) — this is the moment
- // we snapshot, NOT the moment we fire.
- function handleNativeSubmit(event) {
- var formEl = event.target;
- if (!formEl || (formEl.tagName || '').toLowerCase() !== 'form') return;
- if (!isFormidableForm(formEl)) return;
-
- var formId = '';
- var m = /^form_(\d+)$/.exec(formEl.id || '');
- if (m) formId = m[1];
-
- // Client-validity gate: trust the pagehide path when the form is valid
- // (or checkValidity is unavailable). NOTE per the source module:
- // Formidable's required-ness is often enforced only server-side, so a
- // form can pass checkValidity() while still blank — the pagehide-time
- // visible-error check is the real safety net here, not this gate alone.
- var pagehideTrusted = true;
- try {
- if (typeof formEl.checkValidity === 'function' && formEl.checkValidity() === false) {
- pagehideTrusted = false;
- }
- } catch (e) {
- // constraint validation unavailable — pagehide's visible-error check
- // still guards this path
- }
-
- armNativeWatcher(formEl, formId, pagehideTrusted);
+ hookJquery();
+ if (!jqueryHooked) {
+ document.addEventListener('DOMContentLoaded', hookJquery, { once: true });
+ window.addEventListener('load', hookJquery, { once: true });
}
-
- document.addEventListener('frmFormComplete', handleAjaxSuccessEvent, true);
- document.addEventListener('frmBeforeFormRedirect', handleAjaxSuccessEvent, true);
- document.addEventListener('submit', handleNativeSubmit, false);
-
+ document.addEventListener('submit', armNativeMessageAttempt, true);
if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', function () {
- processDeferredVerdict();
- });
+ document.addEventListener('DOMContentLoaded', processNativeMessage, { once: true });
} else {
- processDeferredVerdict();
+ processNativeMessage();
}
})();
diff --git a/skills/conversion-tracking/assets/snippets/forminator.js b/skills/conversion-tracking/assets/snippets/forminator.js
index d9554c0..a91df92 100644
--- a/skills/conversion-tracking/assets/snippets/forminator.js
+++ b/skills/conversion-tracking/assets/snippets/forminator.js
@@ -2,53 +2,62 @@
* Detects: form submission. Pushes dataLayer event: forminator_form_submitted
* From the conversion-tracking skill in Marketing Skills */
(function () {
- if (window.__ctDetectForminator) return;
- window.__ctDetectForminator = true;
+ if (window.__ctForminatorForms) return;
+ window.__ctForminatorForms = true;
window.dataLayer = window.dataLayer || [];
-
- function fireConversion(formId) {
- window.dataLayer.push({
- event: 'forminator_form_submitted',
- form_id: formId || ''
- });
+ var listeners=[],lastEvent=null;
+ window.__ctForminatorSubscribe=function(listener){if(listener&&typeof listener==='object')listeners.push(listener);};
+ function isForm(form){
+ try{return !!(form&&String(form.tagName||'').toLowerCase()==='form'&&form.classList&&form.classList.contains('forminator-custom-form'));}
+ catch(e){return false;}
}
-
- // Fire path — Forminator's own jQuery event, fired on `document` once an
- // AJAX submission passes server-side validation. This is the ONLY path
- // that ever fires a conversion; Forminator clears form fields before this
- // event, but we don't need field values, so that doesn't affect us.
- //
- // Form ID resolution: live-verified against a real Forminator install
- // (2026-07-02) that the `response` argument Forminator hands to this
- // event is an EMPTY object ({}) — response.form_id does not exist in
- // practice, despite being documented elsewhere. The reliable source is
- // `event.target`, which jQuery sets to the <form> element itself (the
- // event bubbles from the form to document), carrying a `data-form-id`
- // attribute Forminator always renders.
- var successHooked = false;
-
- function hookForminatorSuccess() {
- if (successHooked) return true;
- if (typeof jQuery === 'undefined' && typeof $ === 'undefined') return false;
-
- var jQ = typeof jQuery !== 'undefined' ? jQuery : $;
- jQ(document).on('forminator:form:submit:success', function (event) {
- var formEl = event && event.target;
- var formId = (formEl && formEl.getAttribute && formEl.getAttribute('data-form-id')) || '';
- fireConversion(formId);
- });
- successHooked = true;
- return true;
+ function notify(phase,form,candidate,event){
+ var handled=false;
+ for(var i=0;i<listeners.length;i++)try{var fn=listeners[i]&&listeners[i][phase];if(typeof fn==='function'&&fn(form,candidate,event)===true)handled=true;}catch(e){}
+ return handled;
}
-
- // Retry hooking on DOMContentLoaded and window load — some sites load
- // jQuery/Forminator very late.
- if (!hookForminatorSuccess()) {
- document.addEventListener('DOMContentLoaded', function () {
- hookForminatorSuccess();
- });
- window.addEventListener('load', function () {
- hookForminatorSuccess();
- });
+ function submit(event){try{var form=event.target;if(isForm(form))notify('beforeAttempt',form,false,event);}catch(e){}}
+ function success(event){
+ try{
+ if(event&&typeof event==='object'&&event===lastEvent)return;
+ lastEvent=event;
+ if(event&&typeof event==='object')setTimeout(function(){if(lastEvent===event)lastEvent=null;},0);
+ var form=event&&event.target;if(!isForm(form))return;
+ if(!notify('onCandidate',form,true,event))window.dataLayer.push({event:'forminator_form_submitted',form_id:form.getAttribute('data-form-id')||''});
+ }catch(e){}
}
+ document.addEventListener('submit',submit,true);
+ // Page-reload forms render their verdict in the returned page instead of
+ // emitting the AJAX event. Read only the confirmation class and form ID.
+ var confirmedForms=[];
+ function nativeConfirmations(){
+ try{
+ var forms=document.querySelectorAll('form.forminator-custom-form:not(.forminator_ajax)');
+ for(var i=0;i<forms.length;i++){
+ var form=forms[i],message=form.querySelector('.forminator-response-message.forminator-success');
+ if(!message||!message.getClientRects().length||confirmedForms.indexOf(form)!==-1)continue;
+ confirmedForms.push(form);
+ success({target:form});
+ }
+ }catch(e){}
+ }
+ function watchNative(){
+ nativeConfirmations();
+ if(window.MutationObserver&&document.documentElement){
+ new MutationObserver(nativeConfirmations).observe(document.documentElement,{childList:true,subtree:true,attributes:true,attributeFilter:['class','style']});
+ }
+ }
+ if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',watchNative);
+ else watchNative();
+ window.addEventListener('load',nativeConfirmations);
+ function hook(){
+ try{
+ if(window.__ctForminatorSuccessHooked)return true;
+ var jq=window.jQuery||(typeof jQuery!=='undefined'?jQuery:(typeof $!=='undefined'?$:null));
+ if(!jq)return false;
+ window.__ctForminatorSuccessHooked=true;
+ jq(document).on('forminator:form:submit:success',success);return true;
+ }catch(e){return false;}
+ }
+ if(!hook()){document.addEventListener('DOMContentLoaded',hook);window.addEventListener('load',hook);}
})();
diff --git a/skills/conversion-tracking/assets/snippets/framer-forms.js b/skills/conversion-tracking/assets/snippets/framer-forms.js
index e97feeb..6e9ef42 100644
--- a/skills/conversion-tracking/assets/snippets/framer-forms.js
+++ b/skills/conversion-tracking/assets/snippets/framer-forms.js
@@ -2,73 +2,93 @@
* Detects: form submission. Pushes dataLayer event: framer_form_submitted
* From the conversion-tracking skill in Marketing Skills */
(function () {
- // SUBMIT-BASED BEST EFFORT. Framer cancels the native submit and sends
- // the form by script, so a bubble-phase listener always sees it cancelled
- // and never fires. This listens in the capture phase, before Framer's own
- // handler runs, and fires on a submit that passes browser validation. It
- // is still submit-based, so a server-side rejection, a spam block or any
- // later custom validation still counts. A 2-second debounce per form only
- // collapses rapid repeats (a double click). Framer documents a
- // framer:formsubmit event, but it fires only when the form has a tracking
- // ID set and isn't documented as success-only, so this doesn't rely on
- // it. For exact counts, set the form to redirect to a thank-you page and
- // use thank-you-page.js instead.
- if (window.__ctDetectFramerForms) return;
- window.__ctDetectFramerForms = true;
+ if (window.__ctFramerForms) return;
+ window.__ctFramerForms = true;
window.dataLayer = window.dataLayer || [];
-
- function fireConversion(formName) {
- window.dataLayer.push({
- event: 'framer_form_submitted',
- form_name: formName || ''
- });
- }
-
- function isFramerForm(formEl) {
- if (!formEl) return false;
- if (formEl.hasAttribute && formEl.hasAttribute('data-framer-name')) return true;
- var cls = typeof formEl.className === 'string' ? formEl.className : '';
- if (/(^|\s)framer-[A-Za-z0-9_-]+/.test(cls)) return true;
+ var listeners = [];
+ var pending = [];
+ window.__ctFramerSubscribe = function (listener) {
+ if (listener && typeof listener === 'object') listeners.push(listener);
+ };
+ function isFramerForm(form) {
try {
- if (formEl.closest && formEl.closest('[data-framer-component-type]')) return true;
- if (formEl.closest && formEl.closest('[data-framer-name]')) return true;
- } catch (e) {
- // .closest not available — fall through
+ if (!form || String(form.tagName || '').toLowerCase() !== 'form') return false;
+ if (form.hasAttribute && form.hasAttribute('data-framer-name')) return true;
+ if (typeof form.className === 'string' && /(^|\s)framer-[A-Za-z0-9_-]+/.test(form.className)) return true;
+ return !!(form.closest && (form.closest('[data-framer-component-type]') || form.closest('[data-framer-name]')));
+ } catch (e) { return false; }
+ }
+ function notify(phase, form, candidate) {
+ var handled = false;
+ for (var i = 0; i < listeners.length; i++) {
+ try {
+ var fn = listeners[i] && listeners[i][phase];
+ if (typeof fn === 'function' && fn(form, candidate) === true) handled = true;
+ } catch (e) {}
}
- return false;
+ return handled;
}
-
- function handleSubmit(event) {
+ function remember(form) {
try {
- var formEl = event.target;
- if (!formEl || (formEl.tagName || '').toLowerCase() !== 'form') return;
- if (!isFramerForm(formEl)) return;
-
- // Constraint validation gate: an invalid form cannot have submitted.
- try {
- if (typeof formEl.checkValidity === 'function' && formEl.checkValidity() === false) return;
- } catch (e) {
- // constraint validation unavailable — fall through
+ if (!isFramerForm(form)) return;
+ for (var i = 0; i < pending.length; i++) {
+ if (pending[i].form === form) return;
}
-
- // Collapse rapid repeats on this same form element. Keyed on the
- // element itself, so two forms with the same name, or no name, don't
- // share a timestamp.
- var now = Date.now();
- if (formEl.__ctFramerLastFire && now - formEl.__ctFramerLastFire < 2000) return;
- formEl.__ctFramerLastFire = now;
-
- var formName = formEl.getAttribute('data-framer-name') || formEl.id || '';
-
- fireConversion(formName);
- } catch (e) {
- // Never throw back into Framer's own form handling.
+ pending.push({ form: form, time: Date.now(), claimed: false });
+ notify('beforeAttempt', form, false);
+ } catch (e) {}
+ }
+ function finish(attempts, accepted) {
+ for (var i = 0; i < attempts.length; i++) {
+ var index = pending.indexOf(attempts[i]);
+ if (index !== -1) pending.splice(index, 1);
}
+ if (!accepted) return;
+ // Concurrent forms cannot be attributed without inspecting answers.
+ // Keep those submissions event-only, with no guessed form name.
+ var form = attempts.length === 1 ? attempts[0].form : null;
+ var name = form ? form.getAttribute('data-framer-name') || form.id || '' : '';
+ if (!form || !notify('onCandidate', form, true)) {
+ window.dataLayer.push({ event: 'framer_form_submitted', form_name: name });
+ }
+ }
+ if (typeof window.fetch === 'function') {
+ var originalFetch = window.fetch;
+ window.fetch = function (input, options) {
+ var attempts = null;
+ try {
+ var url = typeof input === 'string' ? input : input && input.url;
+ var method = options && options.method || input && input.method || 'GET';
+ if (String(method).toUpperCase() === 'POST' && /^https:\/\/api\.framer\.com\/forms\/v1\/forms\/[a-f0-9-]+\/submit(?:\?.*)?$/.test(url || '')) {
+ attempts = [];
+ var now = Date.now();
+ pending = pending.filter(function (attempt) { return now - attempt.time < 60000; });
+ for (var i = 0; i < pending.length; i++) {
+ if (!pending[i].claimed) {
+ pending[i].claimed = true;
+ attempts.push(pending[i]);
+ }
+ }
+ }
+ } catch (e) {}
+ var result = originalFetch.apply(this, arguments);
+ if (attempts) result.then(function (response) {
+ try { finish(attempts, response.ok === true); } catch (e) {}
+ }, function () {
+ try { finish(attempts, false); } catch (e) {}
+ });
+ return result;
+ };
}
-
if (typeof document !== 'undefined' && document.addEventListener) {
- // Capture phase, so this runs before Framer's own handler cancels the
- // native submit.
- document.addEventListener('submit', handleSubmit, true);
+ document.addEventListener('submit', function (event) { remember(event.target); }, true);
+ // Framer handles Enter directly instead of dispatching native submit.
+ document.addEventListener('keydown', function (event) {
+ var target = event.target;
+ if (event.key === 'Enter' && target && String(target.tagName).toLowerCase() !== 'textarea') {
+ var form = target.form;
+ if (isFramerForm(form) && form.matches(':valid')) remember(form);
+ }
+ }, true);
}
})();
diff --git a/skills/conversion-tracking/assets/snippets/gravity-forms.js b/skills/conversion-tracking/assets/snippets/gravity-forms.js
index 883911f..8d62b01 100644
--- a/skills/conversion-tracking/assets/snippets/gravity-forms.js
+++ b/skills/conversion-tracking/assets/snippets/gravity-forms.js
@@ -1,76 +1,232 @@
/*! Gravity Forms conversion detection (MIT)
* Detects: form submission. Pushes dataLayer event: gravity_form_submitted
* From the conversion-tracking skill in Marketing Skills */
-(function () {
- if (window.__ctDetectGravityForms) return;
- window.__ctDetectGravityForms = true;
- window.dataLayer = window.dataLayer || [];
+/* Gravity Forms Submission Listener.
+ * Event-only adaptation of verified production detection helpers.
+ * Source SHA256 3ed591d48dc449e94fd48f634bb07ae8285f5d661a4b48fc5db867ca3e659b69.
+ * Reads no form field values. Sends only event and form_id to dataLayer.
+ * Native handoff stores only form ID, source path and time in sessionStorage.
+ */
+(function(){
+"use strict";
+if(window.__ctGalleryGravityForms)return;
+window.__ctGalleryGravityForms=true;
+// Preserve the original recipe guard for an old recipe loaded after this code.
+// Do not return on the legacy guard: an old-first listener is independently
+// active and remains an unsupported migration state, but must not suppress us.
+window.__ctDetectGravityForms=true;
+function isGravityForm(formEl) {
+ if (!formEl) return false;
+ // Check for gform_wrapper parent or gform_ ID prefix
+ try {
+ if (formEl.closest && formEl.closest('.gform_wrapper')) return true;
+ } catch (e) {
+ // .closest not available — fall back to ID check
+ }
+ // Fallback: GF forms have IDs like "gform_1", "gform_5"
+ var id = formEl.id || '';
+ return /^gform_\d+$/.test(id);
+ }
- // Dedup between the two fire paths. On a normal setup BOTH paths see the
- // same submission (the jQuery event fires first, the MutationObserver a few
- // milliseconds later — live-verified), and the two report the form id with
- // different types (number vs string), so we dedup on time, not on id: any
- // fire within 3s of the last one is the same submission. A genuine second
- // submission can't complete inside 3s (it needs a refill plus a server
- // round trip).
- var lastFiredAt = 0;
- var DEDUP_WINDOW_MS = 3000;
+function getFormId(formEl) {
+ if (!formEl) return null;
+ var fid = (formEl.getAttribute && formEl.getAttribute('data-formid')) || '';
+ if (fid) return String(fid);
+ var id = formEl.id || '';
+ var m = /gform_(\d+)/.exec(id);
+ return m ? m[1] : null;
+ }
- function fireConversion(formId) {
- var now = Date.now();
- if (now - lastFiredAt < DEDUP_WINDOW_MS) return;
- lastFiredAt = now;
- window.dataLayer.push({
- event: 'gravity_form_submitted',
- form_id: String(formId || '')
- });
+function isAjaxForm(formEl) {
+ if (!formEl) return false;
+ try {
+ var target = (formEl.getAttribute && formEl.getAttribute('target')) || '';
+ if (target.indexOf('gform_ajax_frame_') === 0) return true;
+ if (formEl.querySelector && formEl.querySelector('input[name="gform_ajax"]')) {
+ return true;
+ }
+ } catch (e) {
+ // DOM access failed — treat as non-AJAX; the reload path is the
+ // safer default (it still only fires on confirmed success).
+ }
+ return false;
}
- // Fire path 1 — GF's own jQuery event, fired on `document` after an AJAX
- // submission's confirmation renders. Covers every GF version that ships
- // jQuery on window.
- function hookConfirmationEvent() {
- if (typeof window.jQuery === 'undefined') return false;
- window.jQuery(document).on('gform_confirmation_loaded', function (event, formId) {
- fireConversion(formId);
- });
- return true;
+function isNodeHidden(el) {
+ try {
+ if (el.hidden) return true;
+ if (el.getAttribute && el.getAttribute('aria-hidden') === 'true') return true;
+ var view = el.ownerDocument && el.ownerDocument.defaultView;
+ if (view && view.getComputedStyle) {
+ var cs = view.getComputedStyle(el);
+ if (cs && (cs.display === 'none' || cs.visibility === 'hidden')) return true;
+ }
+ } catch (e) {
+ // fall through
+ }
+ return false;
}
- // Fire path 2 — MutationObserver fallback for setups where window.jQuery
- // isn't reachable. GF replaces the form wrapper with a
- // .gform_confirmation_message element on AJAX success; the form id is
- // encoded in its id attribute (gform_confirmation_message_5).
- function checkNode(node) {
- if (!node || node.nodeType !== 1) return;
- var conf = null;
- if (node.classList && node.classList.contains('gform_confirmation_message')) {
- conf = node;
- } else if (node.querySelector) {
- conf = node.querySelector('.gform_confirmation_message, [id^="gform_confirmation_message_"]');
+function hasVisibleValidationErrors(rootEl) {
+ if (!rootEl || !rootEl.querySelectorAll) return false;
+ try {
+ if (rootEl.className &&
+ (' ' + rootEl.className + ' ').indexOf(' gform_validation_error ') !== -1) {
+ return true;
+ }
+ var nodes = rootEl.querySelectorAll(
+ '.gform_validation_errors, .validation_error, .gfield_error, .validation_message, [aria-invalid="true"]'
+ );
+ for (var i = 0; i < nodes.length; i++) {
+ var node = nodes[i];
+ if (isNodeHidden(node)) continue;
+ if (node.getAttribute && node.getAttribute('aria-invalid') === 'true') return true;
+ // Error classes and ARIA state are structural signals. Never read
+ // rendered validation text: themes may include resolved field values.
+ var classes = typeof node.className === 'string' ? node.className : '';
+ if (/^(?:.*\s)?(?:gform_validation_errors|validation_error|gfield_error)(?:\s.*)?$/.test(classes)) return true;
+ }
+ } catch (e) {
+ // fall through
}
- if (!conf) return;
- var m = /gform_confirmation_message_(\d+)/.exec(conf.id || '');
- fireConversion(m ? m[1] : '');
+ return false;
}
- function observeConfirmations() {
- if (typeof MutationObserver === 'undefined') return;
- var observer = new MutationObserver(function (muts) {
- for (var i = 0; i < muts.length; i++) {
- var added = muts[i].addedNodes;
- if (!added) continue;
- for (var j = 0; j < added.length; j++) checkNode(added[j]);
+function safeFormId(formId) {
+ if (formId == null) return null;
+ var s = String(formId);
+ return /^\d+$/.test(s) ? s : null;
+ }
+
+function hasServerRejectionMarkers(formId) {
+ var fid = safeFormId(formId);
+ try {
+ if (fid) {
+ var scope = document.querySelector('#gform_wrapper_' + fid) ||
+ document.querySelector('#gform_' + fid + ', form[data-formid="' + fid + '"]');
+ if (scope && scope.closest) {
+ scope = scope.closest('.gform_wrapper') || scope;
+ }
+ // The submitted form isn't on this page at all → no rejection
+ // evidence FOR THIS FORM, whatever other forms are showing.
+ return scope ? hasVisibleValidationErrors(scope) : false;
}
- });
- observer.observe(document.body || document.documentElement, {
- childList: true,
- subtree: true
- });
+ var wrappers = document.querySelectorAll('.gform_wrapper');
+ for (var i = 0; i < wrappers.length; i++) {
+ if (hasVisibleValidationErrors(wrappers[i])) return true;
+ }
+ } catch (e) {
+ // fall through
+ }
+ return false;
}
- if (!hookConfirmationEvent()) {
- window.addEventListener('load', hookConfirmationEvent);
+function hasConfirmationMessage(formId) {
+ var fid = safeFormId(formId);
+ try {
+ var nodes = document.querySelectorAll(
+ '.gform_confirmation_message, [id^="gform_confirmation_message_"], [id^="gform_confirmation_wrapper_"]'
+ );
+ for (var i = 0; i < nodes.length; i++) {
+ var node = nodes[i];
+ if (isNodeHidden(node)) continue;
+ // Presence of a visible, form-attributed confirmation element is a
+ // structural legacy signal; its rendered contents are never inspected.
+ if (!fid) continue;
+ // Attribute the node to a form id if it carries one (own id or an
+ // ancestor confirmation-wrapper id).
+ var taggedId = null;
+ var m = /gform_confirmation_(?:message|wrapper)_(\d+)/.exec(node.id || '');
+ if (m) {
+ taggedId = m[1];
+ } else if (node.closest) {
+ try {
+ var anc = node.closest('[id^="gform_confirmation_wrapper_"], [id^="gform_confirmation_message_"]');
+ var am = anc && /_(\d+)$/.exec(anc.id || '');
+ if (am) taggedId = am[1];
+ } catch (e2) {
+ // .closest unavailable — treat as untagged
+ }
+ }
+ if (taggedId === fid) return true;
+ }
+ } catch (e) {
+ // fall through
+ }
+ return false;
}
- observeConfirmations();
+var pending={},complete={},TTL=120000,markerKey='__ct_gallery_gf_pending_v3';
+var modernHookInstalled=false,seenEntries={};
+window.dataLayer=window.dataLayer||[];
+function forget(id){var entry=pending[id];if(entry&&entry.timer)clearTimeout(entry.timer);delete pending[id];}
+function discardNotice(id,reason,form){try{document.dispatchEvent(new CustomEvent('ct:gform-attempt-discarded',{detail:{formId:String(id||''),reason:reason||'discarded',form:form||null}}));}catch(e){}}
+function emitConfirmed(id,form,uniqueAccepted){id=safeFormId(id);if(!id||(!uniqueAccepted&&complete[id]))return;complete[id]=true;var handled=false;try{if(typeof window.__ctGravityMethod2Emit==='function')handled=window.__ctGravityMethod2Emit(id,form)===true;}catch(e){}if(!handled)window.dataLayer.push({event:'gravity_form_submitted',form_id:id});}
+function fireLegacy(id){id=safeFormId(id);if(modernHookInstalled||!id||!pending[id]||complete[id])return;var form=pending[id].form;forget(id);emitConfirmed(id,form);}
+function attempt(form,method,type){
+ if(!isGravityForm(form))return;var id=safeFormId(getFormId(form));if(!id)return;
+ if(modernHookInstalled){return;}
+ if(type&&type!=='submit'){forget(id);discardNotice(id,'nonfinal');return;}
+ forget(id);complete[id]=false;
+ var entry={form:form,method:method||(isAjaxForm(form)?'iframe':'postback'),trusted:method==='postback',time:Date.now(),path:location.pathname,timer:null};
+ entry.timer=setTimeout(function(){if(pending[id]===entry){forget(id);discardNotice(id,'timeout');}},TTL);pending[id]=entry;
+}
+function acceptedIframe(frame){
+ if(modernHookInstalled||!frame||frame.tagName!=='IFRAME'||!/^gform_ajax_frame_\d+$/.test(frame.id||''))return;
+ var id=frame.id.replace('gform_ajax_frame_','');if(!pending[id])return;
+ try{var doc=frame.contentDocument;if(!doc||!doc.querySelector('.GF_AJAX_POSTBACK'))return;if(doc.querySelector('.gform_validation_error, .gform_validation_errors, .gfield_error, [aria-invalid=\"true\"]')){forget(id);discardNotice(id,'rejected');return;}var confirmation=doc.querySelector('#gform_confirmation_wrapper_'+id+', #gform_confirmation_message_'+id);if(confirmation&&!isNodeHidden(confirmation))fireLegacy(id);}catch(e){}
+}
+document.addEventListener('load',function(event){acceptedIframe(event.target);},true);
+var jqueryHooked=false;
+function hook(){
+ if(!jqueryHooked&&typeof window.jQuery==='function'){jqueryHooked=true;window.jQuery(document).on('gform_confirmation_loaded.ctGallery',function(event,id){fireLegacy(id);});}
+ if(modernHookInstalled||!window.gform||!gform.utils||!gform.utils.addAsyncFilter)return;
+ modernHookInstalled=true;
+ gform.utils.addAsyncFilter('gform/submission/pre_submission',function(data){
+ var form=data&&data.form;if(form&&!form.tagName&&form[0])form=form[0];var id=safeFormId(getFormId(form));
+ if(!id)return data;
+ if(data.submissionType!=='submit'){
+ discardNotice(id,'nonfinal',form);
+ return data;
+ }
+ if(data.abort===true)return data;
+ if(data.submissionMethod==='postback'||data.submissionMethod==='iframe')data.submissionMethod='ajax';
+ return data;
+ });
+ gform.utils.addAsyncFilter('gform/submission/submission_started',function(data){
+ var form=data&&data.form;if(form&&!form.tagName&&form[0])form=form[0];var id=safeFormId(getFormId(form));
+ if(id&&data.submissionType==='submit')complete[id]=false;
+ return data;
+ });
+ gform.utils.addAsyncFilter('gform/ajax/post_ajax_submission',function(data){
+ var form=data&&data.form;if(form&&!form.tagName&&form[0])form=form[0];var id=safeFormId(getFormId(form));if(!id)return data;
+ var result=data&&data.submissionResult,verdict=result&&result.data;
+ var rawEntryId=verdict&&verdict.entry_id,entryId=typeof rawEntryId==='number'?rawEntryId:(typeof rawEntryId==='string'&&/^\d+$/.test(rawEntryId)?Number(rawEntryId):NaN);
+ var key=id+':'+entryId;
+ if(result&&result.success===true&&verdict&&verdict.is_valid===true&&verdict.submission_type==='submit'&&isFinite(entryId)&&Math.floor(entryId)===entryId&&entryId>0&&entryId<=9007199254740991&&verdict.is_spam===false){
+ if(seenEntries[key]){discardNotice(id,'duplicate-entry',form);return data;}
+ seenEntries[key]=true;emitConfirmed(id,form,true);
+ }else if(result&&result.success===true)discardNotice(id,'rejected',form);
+ return data;
+ });
+ gform.utils.addAsyncFilter('gform/ajax/pre_display_error',function(data){
+ if(data&&data.formId){var errorForm=null;try{errorForm=document.querySelector('#gform_'+safeFormId(data.formId));}catch(e){}discardNotice(data.formId,'ajax-error',errorForm);}
+ return data;
+ });
+ document.addEventListener('gform/submission/submission_aborted',function(event){
+ var form=event&&event.detail&&event.detail.form,id=safeFormId(getFormId(form));
+ if(id)discardNotice(id,'abort',form);
+ });
+}
+hook();document.addEventListener('gform/theme/scripts_loaded',hook);document.addEventListener('DOMContentLoaded',hook);window.addEventListener('load',hook);
+document.addEventListener('submit',function(event){attempt(event.target,null,'submit');},true);
+document.addEventListener('click',function(event){var el=event.target;if(!el||!el.closest)return;var control=el.closest('[id^="gform_submit_button_"]');if(control)attempt(control.closest('form'),null,'submit');},true);
+function confirmationNode(node){if(modernHookInstalled||!node||node.nodeType!==1)return;var nodes=[];if(node.matches&&node.matches('[id^="gform_confirmation_message_"], [id^="gform_confirmation_wrapper_"]'))nodes.push(node);if(node.querySelectorAll){var list=node.querySelectorAll('[id^="gform_confirmation_message_"], [id^="gform_confirmation_wrapper_"]');for(var i=0;i<list.length;i++)nodes.push(list[i]);}for(var j=0;j<nodes.length;j++){var match=/gform_confirmation_(?:message|wrapper)_(\d+)/.exec(nodes[j].id||'');if(match&&!isNodeHidden(nodes[j]))fireLegacy(match[1]);}}
+if(typeof MutationObserver==='function')new MutationObserver(function(mutations){for(var i=0;i<mutations.length;i++)for(var j=0;j<mutations[i].addedNodes.length;j++)confirmationNode(mutations[i].addedNodes[j]);}).observe(document.body||document.documentElement,{childList:true,subtree:true});
+window.addEventListener('pagehide',function(){
+ var markers=[];for(var id2 in pending)if(Object.prototype.hasOwnProperty.call(pending,id2)){var entry=pending[id2];if(entry.method!=='postback'||Date.now()-entry.time>10000||(!entry.trusted&&hasVisibleValidationErrors(entry.form)))continue;markers.push({id:id2,time:entry.time,path:entry.path});}
+ if(markers.length)try{sessionStorage.setItem(markerKey,JSON.stringify(markers));}catch(e){}
+});
+function deferred(){if(modernHookInstalled)return;var markers;try{var raw=sessionStorage.getItem(markerKey);sessionStorage.removeItem(markerKey);markers=JSON.parse(raw||'[]');}catch(e){return;}if(!Array.isArray(markers))return;for(var i=0;i<markers.length;i++){var marker=markers[i],id=safeFormId(marker&&marker.id);if(!id||!marker.time||Date.now()-marker.time>60000)continue;if(hasServerRejectionMarkers(id))continue;if(hasConfirmationMessage(id)){pending[id]={};fireLegacy(id);}}}
+if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',deferred);else deferred();
+
})();
diff --git a/skills/conversion-tracking/assets/snippets/jotform.js b/skills/conversion-tracking/assets/snippets/jotform.js
index 1ab2ced..f42cd0b 100644
--- a/skills/conversion-tracking/assets/snippets/jotform.js
+++ b/skills/conversion-tracking/assets/snippets/jotform.js
@@ -1,149 +1,30 @@
/*! Jotform conversion detection (MIT)
* Detects: form submission. Pushes dataLayer event: jotform_form_submitted
* From the conversion-tracking skill in Marketing Skills */
+/* Jotform iframe completion listener. Reads no form answers.
+ * Counts once per embedded frame on this page. */
(function () {
- if (window.__ctDetectJotform) return;
+ 'use strict';
+ if (window.__ctDetectJotform || window.__ctJotformMethod2Installed) return;
window.__ctDetectJotform = true;
- window.dataLayer = window.dataLayer || [];
-
- // Two embed styles, two signals of different strength:
- //
- // 1. IFRAME embed (the default Jotform embed code). Jotform doesn't
- // document any submission message from its embed. In testing a classic
- // form, nothing reached the host page after submit, and Jotform's own
- // embed script handles that message only for Card-layout forms. A form
- // showing an on-page thank-you message wasn't tested. So for iframe
- // embeds, set the form's thank-you to redirect to a page on this site
- // and use thank-you-page.js there. Use one method or the other for a
- // given form, never both. The message listener below is kept only as a
- // fallback. It fires only for a message from a Jotform iframe on this
- // page that shows the same form ID, and at most once per form.
- //
- // 2. SOURCE-CODE embed (the form's raw HTML pasted into the page, a
- // <form class="jotform-form"> posting to submit.jotform.com). Jotform
- // validates in its own handler, cancels every native submit and then
- // submits the form itself, so a listener that skips cancelled submits
- // never fires. This path marks the form on submit (capture phase) and
- // fires when the browser builds the form's data for the real send (the
- // formdata event), once per form. In the tested flow (a classic form
- // with Jotform's own validation on), a submit Jotform rejects builds no
- // data and doesn't count. A server-side rejection or spam block after
- // the send still counts.
- // Known limits. If another script builds the form's data after a
- // rejected attempt, that counts. Payment, multi-page, save-and-continue
- // and captcha forms haven't been tested, so prefer the thank-you
- // redirect plus thank-you-page.js there.
-
- var JOTFORM_FORM_ID_RE = /^\d{10,}$/;
- var JOTFORM_SUBMIT_ACTION_RE = /^https?:\/\/submit\.jotform\.com\//i;
- var JOTFORM_ORIGIN_RE = /(^|\.)jotform(eu)?\.com$/;
-
- // Form IDs already counted on this page, shared by both paths.
- var fired = {};
-
- function fireConversion(formId) {
- window.dataLayer.push({
- event: 'jotform_form_submitted',
- form_id: formId || ''
- });
- }
-
- // ---- Path 1: iframe embed, message listener kept as a fallback ----
-
- // True when the iframe's src is a Jotform form host and one of its path
- // segments is exactly this form ID.
- function frameShowsForm(frame, formId) {
- var src = (frame.getAttribute && frame.getAttribute('src')) || '';
- if (!src) return false;
- var url;
- try {
- url = new URL(src, window.location.href);
- } catch (e) {
- return false;
- }
- if (!JOTFORM_ORIGIN_RE.test(url.hostname.toLowerCase())) return false;
- var parts = url.pathname.split('/');
- for (var i = 0; i < parts.length; i++) {
- if (parts[i] === formId) return true;
- }
- return false;
- }
-
- // Frames are looked up when the message arrives, so an iframe inserted
- // after this snippet loaded still binds.
- function sourceIsFormFrame(source, formId) {
- var frames = document.getElementsByTagName('iframe');
+ window.__ctJotformMethod2Installed = true;
+ var completed = [];
+ window.addEventListener('message', function (event) {
+ if (!event.source || event.source === window) return;
+ if (!/^https:\/\/(form|submit)\.jotform\.com$/.test(event.origin)) return;
+ var data = event.data;
+ if (!data || typeof data !== 'object' || Array.isArray(data) || data.action !== 'submission-completed') return;
+ var frames = document.querySelectorAll('iframe');
for (var i = 0; i < frames.length; i++) {
- var win = null;
- try { win = frames[i].contentWindow; } catch (e) { win = null; }
- if (win && win === source && frameShowsForm(frames[i], formId)) return true;
- }
- return false;
- }
-
- function handleMessage(event) {
- try {
- if (!event || !event.source || event.source === window) return;
- if (!event.origin || typeof event.origin !== 'string') return;
- var hostMatch = /^https:\/\/([^/]+)$/.exec(event.origin);
- if (!hostMatch || !JOTFORM_ORIGIN_RE.test(hostMatch[1])) return;
-
- var data = event.data;
- if (typeof data === 'string') {
- if (data.indexOf('submission-completed') === -1) return;
- try { data = JSON.parse(data); } catch (e) { return; }
- }
- if (!data || typeof data !== 'object') return;
- if (data.action !== 'submission-completed') return;
-
- var formId = String(data.formID || data.formId || '');
- if (!JOTFORM_FORM_ID_RE.test(formId)) return;
- if (fired[formId]) return;
- if (!sourceIsFormFrame(event.source, formId)) return;
-
- fireConversion(formId);
- fired[formId] = true;
- } catch (e) {
- // Never throw back into the page's own message handling.
- }
- }
-
- window.addEventListener('message', handleMessage, false);
-
- // ---- Path 2: source-code embed, submission built ----
-
- function isJotformInlineForm(formEl) {
- if (!formEl || (formEl.tagName || '').toLowerCase() !== 'form') return false;
- var hasClass = formEl.classList && formEl.classList.contains('jotform-form');
- var action = formEl.getAttribute && formEl.getAttribute('action');
- var hasAction = action && JOTFORM_SUBMIT_ACTION_RE.test(action);
- if (!hasClass && !hasAction) return false;
- var id = formEl.id || '';
- if (!JOTFORM_FORM_ID_RE.test(id)) return false;
- return true;
- }
-
- var attempted = {};
-
- // Capture phase, so this sees the submit before Jotform cancels it.
- document.addEventListener('submit', function (event) {
- var formEl = event.target;
- if (!isJotformInlineForm(formEl)) return;
- attempted[formEl.id] = true;
- }, true);
-
- // Chromium can raise formdata twice for one submission, so the fired
- // check is what keeps this to one conversion per form. The form is marked
- // fired only after the push succeeds.
- document.addEventListener('formdata', function (event) {
- try {
- var formEl = event.target;
- if (!isJotformInlineForm(formEl)) return;
- if (!attempted[formEl.id] || fired[formEl.id]) return;
- fireConversion(formEl.id);
- fired[formEl.id] = true;
- } catch (e) {
- // Never throw back into Jotform's own submit handling.
+ var frame = frames[i];
+ if (frame.contentWindow !== event.source) continue;
+ var match = /^https:\/\/form\.jotform\.com\/(\d+)(?:[/?#]|$)/.exec(frame.getAttribute('src') || '');
+ if (!match || (data.formID != null && String(data.formID) !== match[1])) return;
+ if (completed.indexOf(frame) !== -1) return;
+ completed.push(frame);
+ window.dataLayer = window.dataLayer || [];
+ window.dataLayer.push({ event: 'jotform_form_submitted', form_id: match[1] });
+ return;
}
- }, true);
+ });
})();
diff --git a/skills/conversion-tracking/assets/snippets/ninja-forms.js b/skills/conversion-tracking/assets/snippets/ninja-forms.js
index 4bd201f..6f2a1f9 100644
--- a/skills/conversion-tracking/assets/snippets/ninja-forms.js
+++ b/skills/conversion-tracking/assets/snippets/ninja-forms.js
@@ -2,117 +2,151 @@
* Detects: form submission. Pushes dataLayer event: ninja_forms_submitted
* From the conversion-tracking skill in Marketing Skills */
(function () {
- if (window.__ctDetectNinjaForms) return;
+ 'use strict';
+ var runtime = window.__ctNinjaFormsRuntime;
+ if (runtime && runtime.installed) return;
+
+ // Preserve the recipe's public duplicate-install guard. If a superseded
+ // snippet already set it without this runtime, fail closed: don't layer a
+ // second listener over an unknown old detector.
+ if (!runtime && window.__ctDetectNinjaForms) return;
+
+ if (!runtime) {
+ runtime = { seenEntryIds: Object.create(null), installed: false };
+ window.__ctNinjaFormsRuntime = runtime;
+ }
window.__ctDetectNinjaForms = true;
window.dataLayer = window.dataLayer || [];
- function fireConversion(formId) {
- window.dataLayer.push({
- event: 'ninja_forms_submitted',
- form_id: formId || ''
- });
+ var MISSING = {};
+ var MAX_SAFE_INTEGER = 9007199254740991;
+
+ // Read only own data properties. Callback payloads are normally parsed JSON,
+ // but a filter or another page script can supply accessor-backed objects.
+ // Do not execute getters while deciding whether a response proves a save.
+ function ownDataValue(object, key) {
+ if (!object || typeof object !== 'object' || !Object.prototype.hasOwnProperty.call(object, key)) return MISSING;
+ if (typeof Object.getOwnPropertyDescriptor !== 'function') return MISSING;
+ var descriptor = Object.getOwnPropertyDescriptor(object, key);
+ if (!descriptor || !Object.prototype.hasOwnProperty.call(descriptor, 'value')) return MISSING;
+ return descriptor.value;
}
- function responseHasErrors(response) {
- if (!response || !response.errors) return false;
- var errors = response.errors;
- if (typeof errors.length === 'number') return errors.length > 0;
- if (typeof errors !== 'object') return !!errors;
- for (var key in errors) {
- if (!Object.prototype.hasOwnProperty.call(errors, key)) continue;
- var group = errors[key];
- if (!group) continue;
- if (typeof group.length === 'number') {
- if (group.length > 0) return true;
- } else if (typeof group === 'object') {
- for (var sub in group) {
- if (Object.prototype.hasOwnProperty.call(group, sub)) return true;
- }
- } else {
- return true;
- }
+ function emptyErrors(value) {
+ if (Object.prototype.toString.call(value) === '[object Array]') return value.length === 0;
+ if (!value || typeof value !== 'object') return false;
+ for (var key in value) {
+ if (Object.prototype.hasOwnProperty.call(value, key)) return false;
}
- return false;
+ return true;
}
- function handleSubmitResponse(response) {
- if (responseHasErrors(response)) return;
- var formId = (response && response.data && response.data.form_id) ? response.data.form_id : '';
- fireConversion(formId);
+ // Accept only primitive safe integers or canonical decimal strings. Never
+ // coerce booleans, arrays, objects, boxed numbers, or accessor-backed IDs.
+ function positiveIntegerId(value) {
+ if (typeof value === 'number') {
+ if (!isFinite(value) || value <= 0 || Math.floor(value) !== value || value > MAX_SAFE_INTEGER) return null;
+ return String(value);
+ }
+ if (typeof value !== 'string' || !/^[1-9]\d*$/.test(value)) return null;
+ var number = Number(value);
+ if (!isFinite(number) || number > MAX_SAFE_INTEGER || String(number) !== value) return null;
+ return value;
}
- var radioHooked = false;
-
- function hookNfRadio() {
- if (radioHooked) return true;
-
- if (typeof nfRadio !== 'undefined' && nfRadio.channel) {
- try {
- nfRadio.channel('forms').on('submit:response', handleSubmitResponse);
- radioHooked = true;
- return true;
- } catch (e) {
- }
+ function canonicalFormId(value) {
+ var formId;
+ if (typeof value === 'number') {
+ if (!isFinite(value) || value <= 0 || Math.floor(value) !== value || value > MAX_SAFE_INTEGER) return null;
+ formId = String(value);
+ } else if (typeof value === 'string') {
+ formId = value;
+ } else {
+ return null;
}
-
- if (typeof Backbone !== 'undefined' && Backbone.Radio) {
- try {
- Backbone.Radio.channel('forms').on('submit:response', handleSubmitResponse);
- radioHooked = true;
- return true;
- } catch (e) {
- }
+ if (!/^[1-9]\d*(?:_(?:0|[1-9]\d*))*$/.test(formId)) return null;
+ var parts = formId.split('_');
+ for (var i = 0; i < parts.length; i++) {
+ var part = Number(parts[i]);
+ if (!isFinite(part) || part > MAX_SAFE_INTEGER || String(part) !== parts[i]) return null;
}
-
- return false;
+ return formId;
}
- var observerStarted = false;
-
- function startMutationObserver() {
- if (observerStarted) return;
- if (typeof MutationObserver === 'undefined') return;
-
- var containers = document.querySelectorAll('.nf-form-cont');
- if (containers.length === 0) return;
-
- observerStarted = true;
+ function inspectResponse(response, callbackFormId) {
+ var errors = ownDataValue(response, 'errors');
+ if (errors === MISSING || !emptyErrors(errors)) return null;
+ var data = ownDataValue(response, 'data');
+ if (!data || typeof data !== 'object') return null;
+ var halt = ownDataValue(data, 'halt');
+ if (halt !== MISSING && halt) return null;
+ var nestedErrors = ownDataValue(data, 'errors');
+ if (nestedErrors !== MISSING && !emptyErrors(nestedErrors)) return null;
+ var formValue = ownDataValue(data, 'form_id');
+ var formId = formValue === MISSING ? null : canonicalFormId(formValue);
+ if (!formId || canonicalFormId(callbackFormId) !== formId) return null;
+ var actions = ownDataValue(data, 'actions');
+ if (!actions || typeof actions !== 'object') return null;
+ var save = ownDataValue(actions, 'save');
+ if (!save || typeof save !== 'object') return null;
+ var saveValue = ownDataValue(save, 'sub_id');
+ var entryId = saveValue === MISSING ? null : positiveIntegerId(saveValue);
+ if (!entryId) return null;
+ return { formId: formId, entryId: entryId };
+ }
- for (var c = 0; c < containers.length; c++) {
- (function (container) {
- var observer = new MutationObserver(function (mutations) {
- for (var m = 0; m < mutations.length; m++) {
- var addedNodes = mutations[m].addedNodes;
- for (var n = 0; n < addedNodes.length; n++) {
- var node = addedNodes[n];
- if (!node || node.nodeType !== 1) continue;
+ runtime.inspectResponse = inspectResponse;
- var isResponseMsg = false;
- if (node.classList && node.classList.contains('nf-response-msg')) {
- isResponseMsg = true;
- } else if (node.querySelector) {
- isResponseMsg = !!node.querySelector('.nf-response-msg');
- }
+ function handleSubmitResponse(response, textStatus, jqXHR, callbackFormId) {
+ var accepted = inspectResponse(response, callbackFormId);
+ if (!accepted) {
+ if (typeof window.__ctNinjaMethod2AfterResponse === 'function') {
+ window.__ctNinjaMethod2AfterResponse(callbackFormId, false, false);
+ }
+ return;
+ }
- if (isResponseMsg) fireConversion('');
- }
- }
- });
+ var key = '$' + accepted.entryId;
+ if (runtime.seenEntryIds[key]) {
+ if (typeof window.__ctNinjaMethod2AfterResponse === 'function') {
+ window.__ctNinjaMethod2AfterResponse(accepted.formId, false, true);
+ }
+ return;
+ }
+ runtime.seenEntryIds[key] = true;
+
+ var enriched = false;
+ if (typeof window.__ctNinjaMethod2Emit === 'function') {
+ try {
+ enriched = window.__ctNinjaMethod2Emit(accepted.formId, accepted.entryId) === true;
+ } catch (e) {
+ enriched = false;
+ }
+ }
+ if (!enriched) {
+ window.dataLayer.push({ event: 'ninja_forms_submitted', form_id: accepted.formId });
+ }
+ if (typeof window.__ctNinjaMethod2AfterResponse === 'function') {
+ window.__ctNinjaMethod2AfterResponse(accepted.formId, true, false);
+ }
+ }
- observer.observe(container, { childList: true, subtree: true });
- })(containers[c]);
+ function hookNfRadio() {
+ if (runtime.installed) return true;
+ var radio = typeof nfRadio !== 'undefined' && nfRadio.channel ? nfRadio :
+ (typeof Backbone !== 'undefined' && Backbone.Radio ? Backbone.Radio : null);
+ if (!radio) return false;
+ try {
+ radio.channel('forms').on('submit:response', handleSubmitResponse);
+ runtime.installed = true;
+ return true;
+ } catch (e) {
+ return false;
}
}
- var hooked = hookNfRadio();
- if (!hooked) {
- document.addEventListener('DOMContentLoaded', function () {
- var retryHooked = hookNfRadio();
- if (!retryHooked) startMutationObserver();
- });
- window.addEventListener('load', function () {
- if (!radioHooked) hookNfRadio();
- if (!observerStarted && !radioHooked) startMutationObserver();
- });
+ if (!hookNfRadio()) {
+ document.addEventListener('DOMContentLoaded', hookNfRadio);
+ window.addEventListener('load', hookNfRadio);
}
})();
diff --git a/skills/conversion-tracking/assets/snippets/tally.js b/skills/conversion-tracking/assets/snippets/tally.js
index c8e5084..1393964 100644
--- a/skills/conversion-tracking/assets/snippets/tally.js
+++ b/skills/conversion-tracking/assets/snippets/tally.js
@@ -1,63 +1,165 @@
/*! Tally conversion detection (MIT)
* Detects: form submission. Pushes dataLayer event: tally_form_submitted
* From the conversion-tracking skill in Marketing Skills */
+/* Tally Submission Listener. Reads only the envelope of Tally's
+ * own submission message; it does not decode or read answer values and never
+ * pushes answers. */
(function () {
- if (window.__ctDetectTally) return;
+ 'use strict';
+ if (window.__ctDetectTally || window.__ctTallyMethod2Installed) return;
window.__ctDetectTally = true;
+ // Keep the historical Method 2 marker as a one-way compatibility alias.
+ // The separate Method 2 adapter has its own marker and can still register
+ // after this core is already installed.
+ window.__ctTallyMethod2Installed = true;
window.dataLayer = window.dataLayer || [];
- function fireConversion(formId, formName) {
- window.dataLayer.push({
- event: 'tally_form_submitted',
- form_id: formId || '',
- form_name: formName || ''
- });
+ function isWs(c) { return c === ' ' || c === '\n' || c === '\r' || c === '\t'; }
+ function skipWs(s, p) { while (p.i < s.length && isWs(s.charAt(p.i))) p.i++; }
+ function stringEnd(s, p, decode) {
+ if (s.charAt(p.i) !== '"') throw new Error('string');
+ var start = p.i++;
+ while (p.i < s.length) {
+ var c = s.charAt(p.i++);
+ if (c === '"') {
+ if (!decode) return null;
+ // Decode only object keys and allowlisted envelope metadata strings.
+ return JSON.parse(s.slice(start, p.i));
+ }
+ if (c.charCodeAt(0) < 0x20) throw new Error('control');
+ if (c === '\\') {
+ if (p.i >= s.length) throw new Error('escape end');
+ var esc = s.charAt(p.i++);
+ if ('"\\/bfnrt'.indexOf(esc) !== -1) continue;
+ if (esc !== 'u' || !/^[0-9a-fA-F]{4}$/.test(s.slice(p.i, p.i + 4))) throw new Error('escape');
+ p.i += 4;
+ }
+ }
+ throw new Error('unterminated');
}
-
- function parseMessageData(data) {
- if (!data) return null;
- if (typeof data === 'string') {
- try {
- return JSON.parse(data);
- } catch (e) {
- return null;
+ function skipValue(s, p, depth) {
+ if (depth > 32) throw new Error('depth');
+ skipWs(s, p);
+ var c = s.charAt(p.i);
+ if (c === '"') { stringEnd(s, p, false); return; }
+ if (c === '{') {
+ p.i++; skipWs(s, p); if (s.charAt(p.i) === '}') { p.i++; return; }
+ while (p.i < s.length) {
+ skipWs(s, p); stringEnd(s, p, false); skipWs(s, p);
+ if (s.charAt(p.i++) !== ':') throw new Error('colon');
+ skipValue(s, p, depth + 1); skipWs(s, p);
+ var sep = s.charAt(p.i++); if (sep === '}') return; if (sep !== ',') throw new Error('object');
}
+ throw new Error('object end');
}
- if (typeof data === 'object') return data;
- return null;
+ if (c === '[') {
+ p.i++; skipWs(s, p); if (s.charAt(p.i) === ']') { p.i++; return; }
+ while (p.i < s.length) {
+ skipValue(s, p, depth + 1); skipWs(s, p);
+ var a = s.charAt(p.i++); if (a === ']') return; if (a !== ',') throw new Error('array');
+ }
+ throw new Error('array end');
+ }
+ var begin = p.i;
+ while (p.i < s.length && !isWs(s.charAt(p.i)) && ',}]'.indexOf(s.charAt(p.i)) === -1) p.i++;
+ if (p.i === begin) throw new Error('value');
+ var token = s.slice(begin, p.i);
+ if (token !== 'true' && token !== 'false' && token !== 'null' &&
+ !/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(token)) throw new Error('primitive');
}
-
- var TALLY_ORIGIN_PATTERN = /(^|\.)tally\.so$/;
-
- function isTrustedOrigin(event) {
- if (!event) return false;
- if (event.source === window) return false;
- if (!event.source) return false;
- if (!event.origin || typeof event.origin !== 'string') return false;
- var hostMatch = /^https:\/\/([^/]+)/.exec(event.origin);
- if (!hostMatch) return false;
- return TALLY_ORIGIN_PATTERN.test(hostMatch[1]);
+ function readStringValue(s, p) { skipWs(s, p); return stringEnd(s, p, true); }
+ function readMetadataObject(s, p, wanted, out) {
+ skipWs(s, p); if (s.charAt(p.i++) !== '{') throw new Error('metadata object');
+ skipWs(s, p); if (s.charAt(p.i) === '}') { p.i++; return; }
+ while (p.i < s.length) {
+ skipWs(s, p); var key = stringEnd(s, p, true); skipWs(s, p);
+ if (s.charAt(p.i++) !== ':') throw new Error('metadata colon');
+ if (wanted[key]) { out[key] = readStringValue(s, p); }
+ else if (key === 'fields') { skipWs(s, p); if (s.charAt(p.i) !== '[') throw new Error('fields shape'); skipValue(s, p, 0); out.fieldsArray = true; }
+ else skipValue(s, p, 0);
+ skipWs(s, p); var sep = s.charAt(p.i++); if (sep === '}') return; if (sep !== ',') throw new Error('metadata separator');
+ }
+ throw new Error('metadata end');
}
-
- function handleMessage(event) {
+ function readEnvelope(s) {
+ if (typeof s !== 'string' || s.length > 1048576) return null;
+ var p = { i: 0 }, out = {}, payload = {};
try {
- if (!event || !event.data) return;
- var msg = parseMessageData(event.data);
- if (!msg) return;
- var eventName = msg.event || msg.type;
- if (eventName !== 'Tally.FormSubmitted') return;
- if (!isTrustedOrigin(event)) return;
-
- var payload = msg.payload || msg.data || msg;
- if (!payload || typeof payload !== 'object' || !Array.isArray(payload.fields)) return;
-
- fireConversion(payload.formId, payload.formName);
- } catch (e) {
- // Never throw back into the page's own message handling.
+ skipWs(s, p); if (s.charAt(p.i++) !== '{') return null;
+ skipWs(s, p); if (s.charAt(p.i) === '}') return null;
+ while (p.i < s.length) {
+ skipWs(s, p); var key = stringEnd(s, p, true); skipWs(s, p);
+ if (s.charAt(p.i++) !== ':') return null;
+ if (key === 'event') out.event = readStringValue(s, p);
+ else if (key === 'payload') readMetadataObject(s, p, { id: true, formId: true }, payload);
+ else skipValue(s, p, 0);
+ skipWs(s, p); var sep = s.charAt(p.i++); if (sep === '}') break; if (sep !== ',') return null;
+ }
+ skipWs(s, p); if (p.i !== s.length) return null;
+ if (out.event !== 'Tally.FormSubmitted') return null;
+ if (!payload.id || !payload.formId || !payload.fieldsArray || !/^[-A-Za-z0-9_]{1,128}$/.test(payload.id) || !/^[-A-Za-z0-9_]{1,128}$/.test(payload.formId)) return null;
+ return { id: payload.id, formId: payload.formId };
+ } catch (e) { return null; }
+ }
+ function isTallyOrigin(origin) {
+ return typeof origin === 'string' && /^https:\/\/tally\.so(?::443)?$/i.test(origin);
+ }
+ // Bind only fixed-host iframe paths using CSS attribute selectors. Do not
+ // retrieve src or data-tally-src: either may contain prefilled respondent
+ // data in its query. Only a materialized iframe src is supported here; a
+ // deferred attribute without a loaded src fails closed.
+ function frameFormId(frame, expectedFormId) {
+ if (!/^[-A-Za-z0-9_]{1,128}$/.test(expectedFormId || '') ||
+ !frame || typeof frame.matches !== 'function') return '';
+ var found = false;
+ var modes = ['embed', 'r', 'popup'];
+ for (var i = 0; i < modes.length; i++) {
+ var base = 'https://tally.so/' + modes[i] + '/' + expectedFormId;
+ var selectors = [
+ 'iframe[src="' + base + '"]',
+ 'iframe[src^="' + base + '?"]',
+ 'iframe[src^="' + base + '#"]'
+ ];
+ for (var j = 0; j < selectors.length; j++) {
+ try { if (frame.matches(selectors[j])) { found = true; break; } }
+ catch (e) { return ''; }
+ }
+ if (found) return expectedFormId;
}
+ return '';
}
-
- if (typeof window !== 'undefined' && window.addEventListener) {
- window.addEventListener('message', handleMessage, false);
+ function renderedFrameFormId(source, expectedFormId) {
+ if (!source || source === window) return '';
+ var frames;
+ try { frames = document.getElementsByTagName('iframe'); } catch (e) { return ''; }
+ for (var i = 0; frames && i < frames.length; i++) {
+ try {
+ if (frames[i].contentWindow === source) {
+ // The event carries only a bounded public form ID. The selector tests
+ // the fixed-host path and exact delimiter without exposing the URL.
+ return frameFormId(frames[i], expectedFormId);
+ }
+ } catch (e) {}
+ }
+ return '';
}
+ var seen = Object.create(null);
+ window.addEventListener('message', function (event) {
+ try {
+ if (!event || !isTallyOrigin(event.origin)) return;
+ var verdict = readEnvelope(event.data);
+ if (!verdict) return;
+ var configuredFormId = renderedFrameFormId(event.source, verdict.formId);
+ if (!configuredFormId || verdict.formId !== configuredFormId) return;
+ var key = verdict.formId + ':' + verdict.id;
+ if (seen[key]) return;
+ seen[key] = true;
+ var handled = false;
+ var adapter = window.__ctTallyMethod2Handler;
+ if (typeof adapter === 'function') {
+ try { handled = adapter(event, verdict) === true; } catch (e) { handled = false; }
+ }
+ if (!handled) window.dataLayer.push({ event: 'tally_form_submitted', form_id: verdict.formId, submission_id: verdict.id });
+ } catch (e) {}
+ }, false);
})();
diff --git a/skills/conversion-tracking/assets/snippets/webflow-forms.js b/skills/conversion-tracking/assets/snippets/webflow-forms.js
index 3229978..d0e4887 100644
--- a/skills/conversion-tracking/assets/snippets/webflow-forms.js
+++ b/skills/conversion-tracking/assets/snippets/webflow-forms.js
@@ -2,119 +2,54 @@
* Detects: form submission. Pushes dataLayer event: webflow_form_submitted
* From the conversion-tracking skill in Marketing Skills */
(function () {
- if (window.__ctDetectWebflowForms) return;
- window.__ctDetectWebflowForms = true;
+ if (window.__ctWebflowForms) return;
+ window.__ctWebflowForms = true;
window.dataLayer = window.dataLayer || [];
-
- // How long after a submit we keep watching for Webflow's success box
- // before giving up. Webflow's AJAX round-trip is normally 1–2 seconds.
- var WATCH_TIMEOUT_MS = 30000;
-
- function fireConversion(formName) {
- window.dataLayer.push({
- event: 'webflow_form_submitted',
- form_name: formName || ''
- });
+ var listeners = [], timeout = 30000;
+ window.__ctWebflowSubscribe = function (listener) {
+ if (listener && typeof listener === 'object') listeners.push(listener);
+ };
+ function isForm(form) {
+ try { return !!(form && String(form.tagName || '').toLowerCase() === 'form' && form.closest && form.closest('.w-form')); }
+ catch (e) { return false; }
}
-
- // Webflow marks every form component with the `.w-form` wrapper class,
- // regardless of theme or custom classes added on top. This is the same
- // check the production module uses to scope its listener to real Webflow
- // forms (and not e.g. a hand-coded <form> elsewhere on the page).
- function isWebflowForm(formEl) {
- if (!formEl || !formEl.closest) return false;
- return formEl.closest('.w-form') !== null;
- }
-
- function isVisible(el) {
- if (!el) return false;
- try {
- return window.getComputedStyle(el).display !== 'none';
- } catch (e) {
- return false;
+ function notify(phase, form, candidate) {
+ var handled = false;
+ for (var i=0;i<listeners.length;i++) {
+ try { var fn=listeners[i] && listeners[i][phase]; if (typeof fn==='function' && fn(form,candidate)===true) handled=true; } catch(e) {}
}
+ return handled;
}
-
- // Arm a success watcher for one form. Fires only when Webflow's own
- // success box (`.w-form-done`, a sibling of the form inside the `.w-form`
- // wrapper) becomes visible — Webflow sets inline `display: block` on it
- // after its AJAX call succeeds (live-verified). A visible `.w-form-fail`
- // (Webflow's failure box), or the timeout elapsing with neither box shown
- // (Webflow's JS can also reject a submission silently, with no UI change
- // at all), tears the watcher down WITHOUT firing. One watcher per form:
- // a re-submit while armed (e.g. a retry after a failure) resets it.
- function armWatcher(formEl, formName) {
- var wrap = formEl.closest('.w-form');
- if (!wrap) return;
- var doneEl = wrap.querySelector('.w-form-done');
- var failEl = wrap.querySelector('.w-form-fail');
- if (!doneEl) return; // nothing to confirm success against — never fire unconfirmed
-
- var prev = formEl.__ctDetectWatch;
- if (prev) prev.teardown();
-
- var state = { fired: false };
- var observer = null;
- var pollTimer = null;
- var killTimer = null;
-
- function teardown() {
- if (state.fired) return;
- state.fired = true;
- if (observer) { try { observer.disconnect(); } catch (e) {} }
- if (pollTimer) clearInterval(pollTimer);
- if (killTimer) clearTimeout(killTimer);
- formEl.__ctDetectWatch = null;
- }
- state.teardown = teardown;
-
- function check() {
- if (state.fired) return;
- if (isVisible(doneEl)) {
- teardown();
- fireConversion(formName); // confirmed Webflow success
- } else if (isVisible(failEl)) {
- teardown(); // confirmed Webflow failure — no conversion
- }
- }
-
- if (typeof MutationObserver === 'function') {
- observer = new MutationObserver(check);
- observer.observe(wrap, {
- attributes: true,
- attributeFilter: ['style', 'class'],
- subtree: true,
- childList: true
- });
- }
- pollTimer = setInterval(check, 300); // belt-and-braces alongside the observer
- killTimer = setTimeout(teardown, WATCH_TIMEOUT_MS);
-
- formEl.__ctDetectWatch = state;
+ function visible(el) { try { return !!el && window.getComputedStyle(el).display !== 'none'; } catch(e) { return false; } }
+ function emit(form) {
+ var name=''; try { name=form.getAttribute('data-name') || form.id || ''; } catch(e) {}
+ if (!notify('onCandidate', form, true)) window.dataLayer.push({event:'webflow_form_submitted',form_name:name});
}
-
- // Attached at the document level in CAPTURE phase so it runs before the
- // handler Webflow attaches in bubble phase — the same technique the
- // production module uses to see the submit reliably. The submit itself
- // never fires the conversion; it only snapshots the form name and arms
- // the success watcher above.
- function handleSubmit(event) {
+ function submit(event) {
try {
- var formEl = event.target;
- if (!formEl || (formEl.tagName || '').toLowerCase() !== 'form') return;
- if (!isWebflowForm(formEl)) return;
-
- // The form's own name/id — set by the site builder in the Webflow
- // Designer, not user-submitted data. Snapshotted at submit time.
- var formName = formEl.getAttribute('data-name') || formEl.id || '';
-
- armWatcher(formEl, formName);
- } catch (e) {
- // Never throw back into Webflow's own form handling.
- }
- }
-
- if (typeof document !== 'undefined' && document.addEventListener) {
- document.addEventListener('submit', handleSubmit, true);
+ var form=event.target; if (!isForm(form)) return;
+ notify('beforeAttempt', form, false);
+ var wrap=form.closest('.w-form'), done=wrap.querySelector('.w-form-done'), fail=wrap.querySelector('.w-form-fail');
+ if (!done) return;
+ var old=form.__ctWebflowWatch;
+ if (old) { notify('onOverlap', form, false); old.cancel(false); form.__ctWebflowWatch=null; }
+ var staleFail=visible(fail), settled=false, observer=null, poll=null, kill=null, jq=window.jQuery;
+ function stop(rejected) { if(settled)return; settled=true; if(observer)try{observer.disconnect();}catch(e){} if(jq)jq(document).off('ajaxComplete',check); if(poll)clearInterval(poll); if(kill)clearTimeout(kill); if(form.__ctWebflowWatch===state)form.__ctWebflowWatch=null; if(rejected)notify('onRejected',form,false); }
+ var state={cancel:function(){stop(false);}};
+ function check() {
+ if(settled)return;
+ // Webflow sets success only after its server accepts the form. A redirect
+ // skips the success box, so check that state after its AJAX callback.
+ var wf=jq && jq(form).data('.w-form');
+ if(wf && wf.form && wf.form[0]===form && wf.redirect && wf.success===true){ stop(); emit(form); return; }
+ if(visible(done)){ stop(); emit(form); return; }
+ if(!visible(fail)){staleFail=false;return;}
+ if(!staleFail)stop(true);
+ }
+ if(typeof MutationObserver==='function'){observer=new MutationObserver(check);observer.observe(wrap,{attributes:true,attributeFilter:['style','class'],subtree:true,childList:true});}
+ if(jq)jq(document).on('ajaxComplete',check);
+ poll=setInterval(check,300); kill=setTimeout(function(){stop(true);},timeout); form.__ctWebflowWatch=state;
+ } catch(e) {}
}
+ if(typeof document!=='undefined'&&document.addEventListener)document.addEventListener('submit',submit,true);
})();
diff --git a/skills/conversion-tracking/assets/snippets/wpforms.js b/skills/conversion-tracking/assets/snippets/wpforms.js
index 9569ea3..21c2f52 100644
--- a/skills/conversion-tracking/assets/snippets/wpforms.js
+++ b/skills/conversion-tracking/assets/snippets/wpforms.js
@@ -1,327 +1,196 @@
/*! WPForms conversion detection (MIT)
* Detects: form submission. Pushes dataLayer event: wpforms_form_submitted
* From the conversion-tracking skill in Marketing Skills */
+/* WPForms listener. Records message and redirect confirmations.
+ * Native redirects use a short-lived submission marker and changed pathname.
+ * Does not read form values, labels, rendered text/HTML, response bodies,
+ * redirect URLs, or URL query strings. */
(function () {
+ 'use strict';
if (window.__ctDetectWpforms) return;
window.__ctDetectWpforms = true;
- // Only run in real http(s) documents. about:blank / srcdoc iframes inherit
- // the parent's origin, so they SHARE sessionStorage — a copy of this script
- // running in one would consume the deferred native-mode marker and, because
- // its pathname can never equal the form page's path, fabricate a fire via
- // the redirect heuristic. Observed live on parkhousesoftware.com (an
- // about:blank iframe stole the marker during verification, 2026-07-05).
if (!/^https?:$/.test(window.location.protocol)) return;
window.dataLayer = window.dataLayer || [];
- var NATIVE_WINDOW_MS = 10000;
- var DEFERRED_MARKER_KEY = '__ctDetectWpformsNativePending';
- var DEFERRED_MARKER_TTL_MS = 60000;
-
- function isWPForm(formEl) {
- if (!formEl) return false;
- try {
- if (formEl.closest && formEl.closest('.wpforms-container')) return true;
- } catch (e) {
- // .closest not available — fall back to ID check
+ var PENDING_KEY = '__ctWpformsNativePendingV1';
+ var PENDING_TTL_MS = 120000;
+
+ function formId(form) {
+ var match = /^wpforms-form-(\d+)$/.exec((form && form.id) || '');
+ return match ? match[1] : null;
+ }
+ function confirmationNode(id) {
+ if (!id || !/^\d+$/.test(id)) return null;
+ try { return document.querySelector('#wpforms-confirmation-' + id); } catch (e) { return null; }
+ }
+ // A delayed callback can run after another callback has already observed
+ // the same inserted node. Deduplicate by node identity, not by form ID, so
+ // a later accepted response with a distinct confirmation node still counts.
+ var supportsWeakSet = typeof WeakSet === 'function';
+ var handledConfirmationNodes = supportsWeakSet ? new WeakSet() : [];
+ function markConfirmationSeen(node) {
+ if (supportsWeakSet) {
+ if (handledConfirmationNodes.has(node)) return false;
+ handledConfirmationNodes.add(node);
+ return true;
}
- var id = formEl.id || '';
- return /^wpforms-form-\d+$/.test(id);
+ if (handledConfirmationNodes.indexOf(node) !== -1) return false;
+ handledConfirmationNodes.push(node);
+ return true;
}
-
- function parseFormId(formEl) {
- var id = (formEl && formEl.id) || '';
- var m = /^wpforms-form-(\d+)$/.exec(id);
- return m ? m[1] : '';
+ function push(id) {
+ if (!id || !/^\d+$/.test(id)) return;
+ window.dataLayer.push({ event: 'wpforms_form_submitted', form_id: id });
}
-
- function fireConversion(formId) {
- window.dataLayer.push({
- event: 'wpforms_form_submitted',
- form_id: formId || ''
- });
- }
-
- // ---- Shared validation-marker check (used by both fire paths) ----
-
- function isNodeHidden(el) {
- try {
- if (el.hidden) return true;
- if (el.getAttribute && el.getAttribute('aria-hidden') === 'true') return true;
- var view = el.ownerDocument && el.ownerDocument.defaultView;
- if (view && view.getComputedStyle) {
- var cs = view.getComputedStyle(el);
- if (cs && (cs.display === 'none' || cs.visibility === 'hidden')) return true;
- }
- } catch (e) {
- // fall through
- }
- return false;
+ // Method 2 owns and pushes its enriched payload. The detector sees only a
+ // literal handled marker; arbitrary objects or PII are never read/forwarded.
+ function emitConfirmed(id, form, mode) {
+ var adapter = window.__ctWpformsMethod2Emit;
+ try { if (typeof adapter === 'function' && adapter(id, form || null, mode) === true) return; } catch (e) {}
+ push(id);
}
-
- function hasVisibleValidationErrors(scopeEl) {
- if (!scopeEl || !scopeEl.querySelectorAll) return false;
- try {
- var nodes = scopeEl.querySelectorAll(
- '.wpforms-error, .wpforms-error-container, [aria-invalid="true"]'
- );
- for (var i = 0; i < nodes.length; i++) {
- var node = nodes[i];
- if (isNodeHidden(node)) continue;
- if (node.getAttribute && node.getAttribute('aria-invalid') === 'true') return true;
- if ((node.textContent || '').trim()) return true;
- }
- } catch (e) {
- // fall through
- }
- return false;
+ function discardAdapterSnapshot(id, form, mode) {
+ var discard = window.__ctWpformsMethod2Discard;
+ try { if (typeof discard === 'function') discard(id, form || null, mode); } catch (e) {}
}
-
- function hasServerRejectionMarkers() {
+ function storePending(id) {
+ if (!id) return;
try {
- var wrappers = document.querySelectorAll('.wpforms-container');
- for (var i = 0; i < wrappers.length; i++) {
- if (hasVisibleValidationErrors(wrappers[i])) return true;
- }
- } catch (e) {
- // fall through
- }
- return false;
+ window.sessionStorage.setItem(PENDING_KEY, JSON.stringify({ id: id, time: Date.now(), path: window.location.pathname }));
+ } catch (e) {}
}
-
- function hasConfirmationMessage() {
+ function takePending() {
try {
- var nodes = document.querySelectorAll(
- '.wpforms-confirmation-container-full, .wpforms-confirmation-container, div[id^="wpforms-confirmation-"]'
- );
- for (var i = 0; i < nodes.length; i++) {
- if (isNodeHidden(nodes[i])) continue;
- if ((nodes[i].textContent || '').trim()) return true;
- }
- } catch (e) {
- // fall through
- }
- return false;
- }
-
- // ---- Fire path 1: AJAX success event ----
-
- var activeWatchers = [];
-
- function findWatcher(formEl) {
- for (var w = 0; w < activeWatchers.length; w++) {
- if (activeWatchers[w].form === formEl) return activeWatchers[w];
- }
- return null;
- }
-
- // An AJAX success disarms any pagehide watcher armed for this form — the
- // 2s dedup flag self-clears but the native watcher would otherwise stay
- // armed for the full 10s window and could re-fire on a later navigation.
- function disarmWatcher(formEl) {
- var existing = findWatcher(formEl);
- if (existing && typeof existing.cleanup === 'function') existing.cleanup();
- }
-
- var successHooked = false;
-
- function hookWpformsSuccess() {
- if (successHooked) return true;
- if (typeof jQuery === 'undefined' && typeof $ === 'undefined') return false;
-
- var jQ = typeof jQuery !== 'undefined' ? jQuery : $;
- jQ(document).on('wpformsAjaxSubmitSuccess', function (event) {
- var formEl = event.target;
- if (!formEl) return;
-
- if (formEl.getAttribute('data-ct-processing') === 'true') return;
- formEl.setAttribute('data-ct-processing', 'true');
- setTimeout(function () { formEl.removeAttribute('data-ct-processing'); }, 2000);
-
- disarmWatcher(formEl);
- fireConversion(parseFormId(formEl));
- });
- successHooked = true;
- return true;
- }
-
- // ---- Fire path 2: native (non-AJAX) pagehide watcher + deferred verdict ----
-
- function writeDeferredMarker(formId) {
- try {
- window.sessionStorage.setItem(DEFERRED_MARKER_KEY, JSON.stringify({
- t: Date.now(),
- path: window.location.pathname,
- formId: formId
- }));
- return true;
- } catch (e) {
- return false;
- }
- }
-
- function takeDeferredMarker() {
- try {
- var raw = window.sessionStorage.getItem(DEFERRED_MARKER_KEY);
+ var raw = window.sessionStorage.getItem(PENDING_KEY);
if (!raw) return null;
- window.sessionStorage.removeItem(DEFERRED_MARKER_KEY);
- var data = JSON.parse(raw);
- if (!data || typeof data !== 'object') return null;
- if (!data.t || Date.now() - data.t > DEFERRED_MARKER_TTL_MS) return null;
- return data;
- } catch (e) {
- try { window.sessionStorage.removeItem(DEFERRED_MARKER_KEY); } catch (e2) {}
- return null;
+ window.sessionStorage.removeItem(PENDING_KEY);
+ var value = JSON.parse(raw);
+ if (!value || !/^\d+$/.test(String(value.id || '')) ||
+ typeof value.time !== 'number' || Date.now() - value.time > PENDING_TTL_MS ||
+ Date.now() < value.time) return null;
+ return { id: String(value.id), path: typeof value.path === 'string' ? value.path : null };
+ } catch (e) { return null; }
+ }
+ function hasVisibleErrors(root) {
+ var errors = root.querySelectorAll('.wpforms-error, .wpforms-error-container, [aria-invalid="true"]');
+ for (var i = 0; i < errors.length; i++) {
+ if (errors[i].getClientRects().length) return true;
}
+ return false;
}
-
- // Runs once at module init on every page load. Consumes the marker the
- // previous page wrote at pagehide (if any) and reads the verdict from the
- // markup WPForms rendered into THIS page. Rejection is checked first: the
- // rejected-POST re-render always carries error markers, so a missed fire
- // here degrades to under-counting, never fabricating.
- function processDeferredVerdict() {
- var marker = takeDeferredMarker();
+ function processNativeVerdict() {
+ var marker = takePending();
if (!marker) return;
-
- if (hasServerRejectionMarkers()) return;
-
- if (hasConfirmationMessage()) {
- fireConversion(marker.formId);
- return;
- }
- // No WPForms markup either way. A success configured to redirect lands
- // on a different path with no confirmation container — treat a changed
- // pathname as that redirect. A rejection can't look like this: the
- // rejected POST always re-renders the form WITH error markers.
- if (marker.path && window.location.pathname !== marker.path) {
- fireConversion(marker.formId);
+ if (hasVisibleErrors(document)) discardAdapterSnapshot(marker.id, null, 'native-no-confirmation');
+ else if (confirmationNode(marker.id)) emitConfirmed(marker.id, null, 'native-message');
+ else if (marker.path && marker.path !== window.location.pathname) {
+ // A clean submit followed by a new page is the redirect confirmation.
+ // An optional Method 2 adapter may attach what it saved on the form page.
+ emitConfirmed(marker.id, null, 'native-redirect');
+ }
+ else discardAdapterSnapshot(marker.id, null, 'native-no-confirmation');
+ }
+
+ // Keep one short-lived navigation watcher per form. Client validation can
+ // cancel submission, so a submit attempt alone must not leave a marker.
+ var nativeWatchers = new WeakMap();
+ document.addEventListener('submit', function (event) {
+ var form = event && event.target;
+ if (!form || (form.tagName || '').toLowerCase() !== 'form') return;
+ var id = formId(form);
+ if (!id) return;
+ var classes = typeof form.className === 'string' ? form.className : '';
+ if (/(^|\s)wpforms-ajax-form(\s|$)/.test(classes)) return;
+ var previous = nativeWatchers.get(form);
+ if (previous) previous();
+ var timer;
+ function cleanup() {
+ window.removeEventListener('pagehide', onPageHide, true);
+ clearTimeout(timer);
+ nativeWatchers.delete(form);
}
- // Same page, no markers either way — ambiguous, do not fire.
- }
-
- function watchForSuccess(formEl, formId, pagehideTrusted) {
- var entry = { form: formEl, refresh: refresh, cleanup: cleanup };
- activeWatchers.push(entry);
-
- var fired = false;
- var timer = null;
- var pagehideArmed = false;
-
function onPageHide() {
- if (fired) return;
- // Click-then-leave guard: a visitor who submitted an invalid form,
- // got blocked, then navigated away produces a pagehide too. Visible
- // error markers mean the submit never went through — do not fire.
- if (hasVisibleValidationErrors(formEl)) return;
- fired = true;
- if (formEl.getAttribute('data-ct-processing') !== 'true') {
- writeDeferredMarker(formId);
- }
cleanup();
+ // A corrected retry can still display the previous server error box.
+ // Use the current client-validation result, without reading answers.
+ var jq = window.jQuery;
+ var validator = typeof jq === 'function' ? jq(form).data('validator') : null;
+ if (validator && validator.errorList) {
+ if (validator.errorList.length) return;
+ } else if (hasVisibleErrors(form)) return;
+ storePending(id);
+ }
+ nativeWatchers.set(form, cleanup);
+ window.addEventListener('pagehide', onPageHide, true);
+ timer = setTimeout(cleanup, 10000);
+ }, true);
+
+ // AJAX message confirmation: the callback alone is ambiguous. Wait until
+ // WPForms has inserted a new, form-attributed confirmation node.
+ var jqueryHooked = false;
+ var redirectEpochByForm = typeof WeakMap === 'function' ? new WeakMap() : null;
+ var seenRedirectEvents = typeof WeakSet === 'function' ? new WeakSet() : [];
+ var seenSuccessEvents = typeof WeakSet === 'function' ? new WeakSet() : [];
+ function markEventSeen(set, event) {
+ if (!event || (typeof event !== 'object' && typeof event !== 'function')) return false;
+ if (typeof WeakSet === 'function' && set instanceof WeakSet) {
+ if (set.has(event)) return false;
+ set.add(event);
+ return true;
}
-
- function armPagehide() {
- if (pagehideArmed) return;
- try {
- window.addEventListener('pagehide', onPageHide, true);
- pagehideArmed = true;
- } catch (e) {
- // fall through
- }
- }
-
- function disarmPagehide() {
- if (!pagehideArmed) return;
- try { window.removeEventListener('pagehide', onPageHide, true); } catch (e) {}
- pagehideArmed = false;
- }
-
- function startTimer() {
- if (timer) clearTimeout(timer);
- // No navigation within the window → either AJAX already fired (page
- // stayed) or the submit was abandoned/rejected. Either way: clean up,
- // do not fire.
- timer = setTimeout(function () {
- if (!fired) cleanup();
- }, NATIVE_WINDOW_MS);
- }
-
- function cleanup() {
- if (timer) { clearTimeout(timer); timer = null; }
- disarmPagehide();
- var idx = activeWatchers.indexOf(entry);
- if (idx !== -1) activeWatchers.splice(idx, 1);
- }
-
- // A later submit on the same form refreshes the snapshot + verdict +
- // timer — a visitor who failed validation, fixed it, and re-submitted
- // inside the window is a fresh attempt.
- function refresh(nextFormId, nextPagehideTrusted) {
- if (fired) return;
- formId = nextFormId;
- if (nextPagehideTrusted) armPagehide();
- else disarmPagehide();
- startTimer();
- }
-
- // Only arm pagehide when the form was client-valid at submit time. An
- // invalid form cannot have submitted, so its pagehide must not confirm.
- if (pagehideTrusted) armPagehide();
- startTimer();
- }
-
- // Bubble-through-capture submit handler: arms the native watcher on every
- // WPForms submit attempt. This fires even when WPForms preventDefaults the
- // submit (the event still dispatches) — this is the moment we snapshot,
- // NOT the moment we fire. Capture phase is required: WPForms' own submit
- // handler stops the event's propagation before it reaches a bubble-phase
- // document listener (verified on a live form in the production module).
- function armNativeWatcher(event) {
- var formEl = event.target;
- if (!formEl || (formEl.tagName || '').toLowerCase() !== 'form') return;
- if (!isWPForm(formEl)) return;
-
- var formId = parseFormId(formEl);
-
- // Client-validity gate: only trust the pagehide path when the form is
- // valid (or checkValidity is unavailable). An invalid form cannot have
- // submitted, so its navigation must not be read as a success.
- var pagehideTrusted = true;
- try {
- if (typeof formEl.checkValidity === 'function' && formEl.checkValidity() === false) {
- pagehideTrusted = false;
- }
- } catch (e) {
- // constraint validation unavailable — the visible-error check at
- // pagehide time still guards this path
- }
-
- var existing = findWatcher(formEl);
- if (existing) {
- existing.refresh(formId, pagehideTrusted);
- return;
- }
-
- watchForSuccess(formEl, formId, pagehideTrusted);
+ if (set.indexOf(event) !== -1) return false;
+ set.push(event);
+ return true;
}
-
- document.addEventListener('submit', armNativeWatcher, true);
-
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', function () {
- processDeferredVerdict();
+ function markRedirectEvent(event) {
+ return markEventSeen(seenRedirectEvents, event);
+ }
+ function hookWpformsEvents() {
+ if (jqueryHooked) return;
+ var jq = window.jQuery || window.$;
+ if (typeof jq !== 'function') return;
+ jqueryHooked = true;
+ jq(document).on('wpformsAjaxSubmitSuccess.ctWpforms', function (event) {
+ if (!markEventSeen(seenSuccessEvents, event)) return;
+ var form = event && event.target;
+ var id = formId(form);
+ if (!id) return;
+ var redirectEpoch = redirectEpochByForm ? (redirectEpochByForm.get(form) || 0) : 0;
+ var before = confirmationNode(id);
+ setTimeout(function () {
+ var after = confirmationNode(id);
+ if (after && after !== before && markConfirmationSeen(after)) {
+ emitConfirmed(id, form, 'ajax-message');
+ } else if (!redirectEpochByForm || (redirectEpochByForm.get(form) || 0) === redirectEpoch) {
+ discardAdapterSnapshot(id, form, 'ajax-no-confirmation');
+ }
+ }, 0);
});
- } else {
- processDeferredVerdict();
- }
-
- hookWpformsSuccess();
- if (!successHooked) {
- document.addEventListener('DOMContentLoaded', function () {
- hookWpformsSuccess();
+ jq(document).on('wpformsAjaxSubmitFailed.ctWpforms wpformsAjaxSubmitError.ctWpforms wpformsAjaxSubmitActionRequired.ctWpforms', function (event) {
+ var form = event && event.target;
+ var id = formId(form);
+ if (id) discardAdapterSnapshot(id, form, 'ajax-rejected');
});
- window.addEventListener('load', function () {
- hookWpformsSuccess();
+ // WPForms 1.6.7 triggers this only after ajax_process_redirect has
+ // produced a nonempty redirect_url from accepted processing. The URL and
+ // response object are intentionally not inspected.
+ jq(document).on('wpformsAjaxSubmitBeforeRedirect.ctWpforms', function (event) {
+ if (!markRedirectEvent(event)) return;
+ var form = event && event.target;
+ var id = formId(form);
+ if (!id) return;
+ if (redirectEpochByForm) redirectEpochByForm.set(form, (redirectEpochByForm.get(form) || 0) + 1);
+ emitConfirmed(id, form, 'ajax-redirect');
});
}
+ function ready() {
+ processNativeVerdict();
+ hookWpformsEvents();
+ }
+ // Let sibling Method 2 tags in the same page task install their enrichment
+ // delegate before a native confirmation verdict is dispatched.
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', ready, { once: true });
+ else setTimeout(ready, 0);
+ document.addEventListener('DOMContentLoaded', hookWpformsEvents, { once: true });
+ window.addEventListener('load', hookWpformsEvents, { once: true });
})();
diff --git a/skills/conversion-tracking/assets/snippets/ws-form.js b/skills/conversion-tracking/assets/snippets/ws-form.js
index 7aa6c62..c3207cc 100644
--- a/skills/conversion-tracking/assets/snippets/ws-form.js
+++ b/skills/conversion-tracking/assets/snippets/ws-form.js
@@ -5,66 +5,51 @@
if (window.__ctDetectWsForm) return;
window.__ctDetectWsForm = true;
window.dataLayer = window.dataLayer || [];
-
- function fireConversion(formId) {
- window.dataLayer.push({
- event: 'ws_form_submitted',
- form_id: formId || ''
- });
- }
-
- // Same form-resolution chain the production module uses to find the
- // form element (it just never used it for anything but PII — here we
- // read a generic, non-PII form_id off whatever it resolves to).
- function resolveForm(event, formObject) {
- var formEl = null;
- try {
- if (formObject && formObject.form_canvas_obj && formObject.form_canvas_obj[0]) {
- formEl = formObject.form_canvas_obj[0].querySelector('form.wsf-form');
- }
- if (!formEl && event && event.target) {
- var target = event.target;
- if ((target.tagName || '').toLowerCase() === 'form') {
- formEl = target;
- } else if (target.querySelector) {
- formEl = target.querySelector('form.wsf-form');
- }
- }
- if (!formEl) {
- formEl = document.querySelector('form.wsf-form');
- }
- } catch (e) {
- // non-fatal — fall through with whatever we have (possibly null)
+ var seenEvents = typeof WeakSet === 'function' ? new WeakSet() : null;
+ var lastSuccessByInstance = {};
+ function unwrap(value) { return value && value.jquery ? value[0] : (value && value[0] && value[0].nodeType ? value[0] : value); }
+ function onAcceptedSubmit(event, formObject, formId, instanceId, formEl) {
+ if (event && seenEvents) {
+ if (seenEvents.has(event)) return;
+ seenEvents.add(event);
+ }
+ var form = unwrap(formEl);
+ if (!form || !form.matches || !form.matches('form.wsf-form')) return;
+ var id;
+ if (typeof formId === 'string') {
+ if (!/^\d+$/.test(formId) || Number(formId) < 1) return;
+ id = formId;
+ } else if (typeof formId === 'number') {
+ if (!isFinite(formId) || Math.floor(formId) !== formId || formId < 1) return;
+ id = String(formId);
+ } else {
+ return;
+ }
+ // WS Form can finish both requests from a double-click. Count the rapid
+ // success callbacks once, without changing the form or reading answers.
+ var instance = typeof instanceId === 'string' || typeof instanceId === 'number' ? instanceId : '';
+ var key = id + ':' + instance;
+ var now = Date.now();
+ if (lastSuccessByInstance[key] !== undefined && now - lastSuccessByInstance[key] < 2000) return;
+ lastSuccessByInstance[key] = now;
+ var adapter = window.__ctWsFormMethod2Emit;
+ if (typeof adapter === 'function') {
+ try { if (adapter(form, id, instanceId) === true) return; }
+ catch (e) { return; }
}
- return formEl;
+ window.dataLayer.push({ event: 'ws_form_submitted', form_id: id });
}
-
- // Fire path — WS Form's own jQuery event, fired on `document` once an
- // AJAX submission passes server-side validation. This is the ONLY path
- // that ever fires a conversion.
- var successHooked = false;
-
- function hookWsFormSuccess() {
- if (successHooked) return true;
- if (typeof jQuery === 'undefined' && typeof $ === 'undefined') return false;
-
- var jQ = typeof jQuery !== 'undefined' ? jQuery : $;
- jQ(document).on('wsf-success', function (event, formObject) {
- var formEl = resolveForm(event, formObject);
- fireConversion(formEl ? (formEl.id || '') : '');
- });
- successHooked = true;
+ var handlerBound = false;
+ function hook() {
+ if (handlerBound) return true;
+ var jq = typeof jQuery !== 'undefined' ? jQuery : (typeof $ !== 'undefined' ? $ : null);
+ if (!jq) return false;
+ jq(document).on('wsf-submit-success', onAcceptedSubmit);
+ handlerBound = true;
return true;
}
-
- // Retry hooking on DOMContentLoaded and window load — some sites load
- // jQuery very late.
- if (!hookWsFormSuccess()) {
- document.addEventListener('DOMContentLoaded', function () {
- hookWsFormSuccess();
- });
- window.addEventListener('load', function () {
- hookWsFormSuccess();
- });
+ if (!hook()) {
+ document.addEventListener('DOMContentLoaded', hook, { once: true });
+ window.addEventListener('load', hook, { once: true });
}
})();
diff --git a/skills/conversion-tracking/references/conversion-moments.md b/skills/conversion-tracking/references/conversion-moments.md
index 64741ea..11cae82 100644
--- a/skills/conversion-tracking/references/conversion-moments.md
+++ b/skills/conversion-tracking/references/conversion-moments.md
@@ -30,7 +30,7 @@ Stacking complications: multi-step forms (only final step converts; step events
- New v4: `js.hsforms.net/forms/embed/<portalId>.js` + `<div class="hs-form-frame" data-form-id=...>`; renders in IFRAME. Real DOM events on window: `hs-form-event:on-ready`, **`hs-form-event:on-submission:success`**, `:failed`, `:on-interaction:navigate`; `event.detail.formId`; helper `window.HubSpotFormsV4` (has getConversionId()).
- Note: `js.hs-scripts.com/<portalId>.js` is the general HubSpot tracking script - presence ≠ ad conversion tracking.
-**Jotform** - iframe (`form.jotform.com/<id>` or script `form.jotform.com/jsform/<id>`). Jotform documents no submit message to the parent page, and in testing a classic form sent none; the Thank You → redirect setting breaks out of the iframe, navigates TOP window to your URL, and can append field values + unique {id} param - redirect is the most robust method. Tags pasted inside the Jotform builder fire on jotform.com's domain (wrong context).
+**Jotform** - iframe (`form.jotform.com/<id>` or script `form.jotform.com/jsform/<id>`). After a successful submission, Jotform's iframe and script embeds send the parent page a `{action: 'submission-completed', formID}` message (live-checked on both, Oct 2026; Jotform support describes it but doesn't formally document it), which `jotform.js` listens for. The full source-code embed sends none. The Thank You → redirect setting breaks out of the iframe, navigates TOP window to your URL, and can append field values + unique {id} param - redirect is the most robust method. Tags pasted inside the Jotform builder fire on jotform.com's domain (wrong context).
**Contact Form 7 (WP)** - always AJAX. Bubbling DOM events on document (plain addEventListener works): **`wpcf7mailsent`** (success - use this), wpcf7submit, wpcf7invalid, wpcf7spam, wpcf7mailfailed. `event.detail` includes contactFormId, inputs (name/value array - usable for enhanced conversions).
@@ -193,12 +193,11 @@ python3 ../scripts/build_recipe.py --tool <slug> --send <google-ads|ga4|meta|lin
| `ws-form` | WS Form | form submission | `ws_form_submitted` |
**Detection confidence.** Most of these fire on the tool's own success event or on a
-confirmed success state, which is exact. Three infer success from a submit.
-`framer-forms` fires on a validated submit, caught before Framer's own handler cancels it.
-The `jotform` source-code embed fires on the submit followed by the form's data being
-built, once per form. The older-forms path in `wix-forms` fires on a submit that was not
-cancelled and passed constraint validation. They cannot know the server accepted the
-submission, so a server error or a spam rejection would still count. Say so if precision
+confirmed success state, which is exact. `framer-forms` fires when Framer's own form
+endpoint answers its request with success. One infers success from a submit. The
+older-forms path in `wix-forms` fires on a submit that was not cancelled and passed
+constraint validation. It cannot know the server accepted the submission, so a server
+error or a spam rejection would still count. Say so if precision
matters to the user.
## Universal patterns