
TIL how to listen to a Hubspot submit form event
For my current project, I need to send data to hubspot via a form. This form is managed by Hubspot and injected in my code during runtime. I cannot modify the sumit button behaviour.
I dealt with this problem by listening the click event when someone clicks on the submit button.
I did it like this in my React component :
class Compo extends React.Component {
componentDidMount() {
// add eventListener after 1 sec to be sure hubspot form is loaded
setTimeout(() =>window.addEventListener('message', this.handleSubmitHubspotForm), 1000);
}
componentWillUnmount() {
//remove event listener when we change to a new page
window.removeEventListener('message', this.handleSubmitHubspotForm)
}
// method to catch event triggered by the submit button
handleSubmitHubspotForm = (event: any) => {
const decodedAndShortenUrl=decodeURI(urlToRedirect);
if (event.data.type==='hsFormCallback'&&event.data.eventName==='onFormSubmit') {
// redirect to a new URL when event is catch
setTimeout(() =>Router.push(decodedAndShortenUrl), 5000)
};
}
Nothing hard here but a quick snippet code reminder for a next time.
Hope it helps.
Enjoy!