Skip to main content

Using Nexl Form Events for Google Analytics Tracking, Iframe Resizing, and More

Using Nexl Form submit event for custom actions on embedded Nexl forms

Habib Ullah avatar
Written by Habib Ullah
Updated over a week ago

When you embed a Nexl form on your website, you can listen for form events sent from the Nexl form iframe to your parent page. This allows you to trigger custom actions such as Google Analytics tracking, changing the page layout, or dynamically adjusting iframe size.


How It Works

When a user submits a Nexl form embedded on your site, the form sends a postMessage event to the parent page. You can capture this event using JavaScript's window.addEventListener("message", ...) API and then run your own custom code.

Here’s the base code:

window.addEventListener("message", function (event) {
if (event.data.type === "formSubmitted") {
/*
* Trigger custom actions on the form submission event.
* Examples:
* - Track the event in Google Analytics
* - Adjust iframe height for confirmation page
*/

// Example: Google Analytics tracking
// gtag('event', 'form_submit', { event_category: 'Nexl Form', event_label: 'Contact Us' });

// Example: Change background color (for demonstration purposes)
const body = document.querySelector("body");
if (body) {
body.style.background = "red";
}
}
});

Example Use Cases

1. Track Form Submissions in Google Analytics

If you use Google Analytics (GA4), you can send a custom event whenever the Nexl form is submitted:

window.addEventListener("message", function (event) {
if (event.data.type === "formSubmitted") {
gtag('event', 'form_submit', {
event_category: 'Nexl Form',
event_label: 'Contact Us'
});
}
});

This helps you measure conversions, form engagement, or marketing campaign performance.


2. Change the Size of the Iframe

If your form’s height changes after submission (e.g., showing a success message), you can dynamically adjust the iframe size:

window.addEventListener("message", function (event) {
if (event.data.type === "formSubmitted") {
const iframe = document.getElementById("nexl-form-iframe");
if (iframe) {
iframe.style.height = "600px"; // adjust as needed
}
}
});

Implementation Steps

  1. Embed your Nexl form in an iframe on your website:

    <iframe id="nexl-form-iframe" src="https://your-nexl-form-url" style="width: 100%; height: 400px;"></iframe>
  2. Add the event listener script on the same page.

  3. Customize the code inside the if (event.data.type === "formSubmitted") block for your specific needs.


Security Notes

  • Always verify the event.origin matches your Nexl form’s domain before taking action, to prevent malicious scripts from triggering events.

  • Example:

    if (event.origin !== "https://forms.nexl.cloud") return;
Did this answer your question?