Filling hidden fields from utm_* params on Squarespace forms

Another chance to sing the praises of Marketo forms over other form builders. Marketo forms are just, well, normal. Others’ forms, by and large, are needlessly weird and obscure.

Take filling fields from UTM params. On a Marketo form, you just set up a field as type Hidden and set it to Autofill from a param like utm_campaign.

Doesn’t matter what the back end Marketo field is called: could be literally utm_campaign, or the more precise last_utm_campaign, or one of those fields with a backstory like UTM_Campaign_Really_Use_This_One_Guys.

Not so with a Squarespace form. There, even if a field is called utm_campaign it’s impossible to fill it from the param utm_campaign. Unless you use the custom JS below, you can only fill from param names that start with SQF_ and are all caps. That’s crazy!

Nobody wants to append SQF_UTM_CAMPAIGN to links. Even if teeeechnically utm_* params aren’t “standard,” they’re so widely supported that they might as well be.

Ideally, you’d pop the Marketo form embed code in a Squarespace code block instead of using Squarespace forms, sidestepping this issue. But maybe someone at your company likes the way Squarespace forms look and/or has an exaggerated belief in the Squarespace ⮕ Marketo integration. If that’s the case, then open Page Settings » Advanced:

And paste this code in the Code Injection pane:

<script>
    const currentURL = new URL(document.location.href);
    for( const [name,value] of currentURL.searchParams ) {        
        if( /^utm_/.test(name) ) {
            const sqfName = `SQF_${name.toUpperCase()}`;
            currentURL.searchParams.set(sqfName, value);
        }
     }
     history.replaceState({}, "", currentURL.href);
</script>

That’ll take care of it.

The code simply copies each standard utm_<name> param to a corresponding SQF_UTM_<name>. (The original utm_<name> param is not removed, so it still works in GA/Clicky/etc.)

Because Squarespace injects your custom code before its default field-filling code, it’ll fill the fields like we want.

I know what you’re thinking, but don’t even bother

Yes, my first thought was also “Just wait for the form to render and set the <input type="hidden" values using JS.”

But that won’t work. It would with a vanilla HTML form, but Squarespace insists on re-filling (in addition to pre-filling) the fields from the querystring when the person clicks submit, so your values will be blanked out. There’s probably a convoluted hack using stopImmediatePropagation(), but it’ll never be easier than the code above.