'hs-form-event:on-ready' firing twice

Hi there, I’m embedding a HS form into Webflow using the developer code embed option:

<script src="https://js-eu1.hsforms.net/forms/embed/developer/{portalID}.js" defer></script>
<div class="hs-form-html" data-region="eu1" data-form-id="{formID}" data-portal-id="{portalID}"></div>

Which works perfectly, however when I add an eventlistener like this

<script>
 window.addEventListener('hs-form-event:on-ready', (event) => {
 const { formId } = event.detail;
 const timestamp = new Date().toISOString();
 console.log(
 `💡 Form ready event fired for Form ID: ${formId} at ${timestamp}`
 );
 });
</script>

I can see that in my Console tab, that it fired twice.

NRak_2-1760534449295.png

What could be causing this?
I want to inject some data dynamically into a hidden field and I’m not sure if this is a realiable way of checking that my form is loaded and ready.

Hey @NRak have you tried looking for the formInstance instead of the formID? My guess is maybe there’s some multiple loads of your form happening due to the webflow implementation.

https://developers.hubspot.com/docs/api-reference/global-form-events/guide

Thanks @TomM2
Unfortunately it’s the same instanceId as well. Here’s my rewritten script to check:

<script>
 window.addEventListener('hs-form-event:on-ready', (event) => {
 const { formId, instanceId } = event.detail;
 const timestamp = new Date().toISOString();

 console.log(
 `💡 Form ready: formId=${formId}, instanceId=${instanceId} at ${timestamp}`
 );
 });
</script>

It looks like it’s still firing twice with the same instanceIds:

If it’s any help, you can inspect the DOM of my test page here

Oh interesting, thanks for sharing!

This still happens when I test the embed code alone in a sandbox. It looks like this may be caused by the server side rendering of the form, there’s two instances of the form ID loading, one is triggered by the load in your DOM and one is triggered by the server side rendering. My guess is this may be intentioanal but I can’t be sure.

@CommunityTeam would it be possible to check with the forms team to check if this is intentional?

Hey @NRak based on my searches, I think the best suggestion for now is to use a “flag” to make sure your code only runs once. — Jaycee

Have you tried something like this?

// This "flag" tracks if our code has run
let formReadyHasRun = false;

window.addEventListener('hs-form-event:on-ready', (event) => {

 // 1. Check the flag. If it's true, stop here.
 if (formReadyHasRun === true) {
 return; 
 }

 // 2. If it's false, run code...
 console.log("Form is ready, running my code!");
 // ... (Your code to inject data goes here) ...

 // 3. ...then, flip the flag to true.
 formReadyHasRun = true;
});

(Note - I used AI to format my code example) — Jaycee