Include form fields as redirect URL parameters on an embedded form

@GMirazchiev3

I took a quick look. For some reason the value for “redirectUrl” is blank.

I’m not sure why the value for “redirectUrl” is blank. For my setup - I’ve added the redirect url in the form under “What should happen if a visitor submits this form” > where I’ve selected an “External link…”

I’m not sure if Hubspot does something different if it is an internal link???

To help troubleshoot you can add a bunch of console logs to see what is going on :slightly_smiling_face: Since the page is redirecting you’ll lose the console.logs. But in chrome developer tools you can go to the settings and select “preserve log” - so you can continue to see the logs after you’ve redircted to the new page.

And just place the script in the head or in the body within <script></script> tags. It doesn’t matter where

Here’s the script with some console logs added

window.addEventListener('message', (event) => {
 if (event.data.type === 'hsFormCallback') {
 console.log(event.data.eventName);
 if (event.data.eventName === 'onFormSubmitted') {
 for (const [key, value] of Object.entries(event?.data?.data)) {
 console.log(`${key}: ${value}`);
 }
 console.log(`REDIRECT URL: ${event?.data?.data?.redirectUrl}`);

 if (event?.data?.data?.redirectUrl && event?.data?.id) {
 const redirectUrl = new URL(event.data.data.redirectUrl);
 const formId = `hsForm_${event.data.id}`;
 const form = document.getElementById(formId);
 if (form) {
 Array.from(form.elements)
 .filter(
 (input) =>
 input.type !== 'hidden' &&
 input.type !== 'submit',
 )
 .forEach((field) =>
 redirectUrl.searchParams.append(
 field.name,
 field.value,
 ),
 );
 window.location = redirectUrl.toString();
 }
 } else {console.log('Do not have a redirect url or id');}
 }
 }
});