Score:1

Add Javascript On Webform Confirmation Page

ng flag

I am using Webform to generate a form on a page. Wherever this form loads, I need to run some javascript to push some data for Google Analytics 4 on two events (any field is focused, form is submitted regardless of validation results).

For that, I am using this code to load my library that contains all the JS.

function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
{
  if ($form['#id'] == 'myform') {
    $form['#attached']['library'][] = 'mymodule/ga_form';
  }
}

This is all working fine, however, I have a 3rd form state where I need to send the chosen value of a select field to GA. This action should occur when the form is validated/submitted and the confirmation page is loaded. I am using the 'URL with the message option' for the confirmation type on the webform settings. Once the confirmation page is loaded, I have access to the data via the URL parameter like that:

/webform/confirmation?data=[webform_submission:values:type]

The problem is that I can't find a way to load my JS file on the webform confirmation page because since the form is not there anymore, my JS file loaded by the form_alter function is not loaded.

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.