How to use the onFormSubmit Global Event

Hi
Im struggling for hours and cant understand why this doesnt work

please help
Here is what I do :
1 - Im adding the Listener code to the Template section of “additional markup…” before </body>
2 - The code looks like this :
window.addEventListener(‘message’, event => {
if(event.data.type === ‘hsFormCallback’ && event.data.eventName === ‘onFormSubmit’) {
$iputherethecodeid.find(‘input[name=“user_agent”]’).val(navigator.userAgent).change();
}
});

Hi @Ilanyrozen

Can you move your code to the HubSpot Embed Code?

For example, you can customise the embed code:

...
hbspt.forms.create({
 portalId: '',
 formId: '',
 onFormSubmit: function($form) {
 // YOUR SCRIPT HERE
 } 
}); 
...

Here’s more detail https://legacydocs.hubspot.com/docs/methods/forms/advanced_form_options

This isn’t practical if you want to use your event listeners on multiple pages.

But, if I want to reuse Custom Form Code (like the example above) I create a Custom Module with the code and then drop the module into my pages.

Does that work for you?

Mike

Hey @Mike_Eastwood,

is there an easy way to get all the fields values when the `onFormSubmit` method gets called? :thinking:

That method has $form object as an argument instead of the data that will be sent to the submission endpoint.

I know it’s possible to listen for messages from the iframe the legacy way

```

event.data.type === ‘hsFormCallback’ && event.data.eventName === ‘onFormSubmit’

```,

but that is also a bit weird, IMO, though at least I can get data from the event object in the latter case. :man_shrugging: