GA Virtual pageview on Webform reload: is there an easier way? I can't believe it was so difficult.

I have Webform and Google Analytics installed. I want to track submissions of my webform, but since it's set to reload current page on submission, I must make use of either Virtual Pageviews or Events. I went with the former.

At first I thought it'll be as easy as using hook_webform_submission_insert()1 and invoking GA code via drupal_add_js() from there, but somehow it didn't work: the hook itself was executed, but JS was never added to the page.

Now I reached the bottom of Google and haven't found any help on this specific case (everybody seems to be using separate "thank you" pages). Fast forward a couple hours, dozen approaches and hundreds of pages, I finally arrived at this working code:



function mymodule_form_alter(&amp;$form, &amp;$form_state, $form_id) {
  //add custom submit callback
  if ($form_id == 'webform_client_form_[node id here]') {
    $form['#submit'][] = 'mymodule_submit_ga';
  }

  //add GA tracking upon successful submission
  if (isset($_SESSION['mymodule_submission_successful']) &amp;&amp;
      $_SESSION['mymodule_submission_successful'] == TRUE) {
    //reset temporary variable
    unset($_SESSION['mymodule_submission_successful']);
    //build JS
    $script = '(function() {';
    $script .= '_gaq.push(["_trackPageview","[virtual page path here]"]);';
    $script .= '})();';
    //add JS somewhere in the end
    drupal_add_js($script, array("type"=&gt;"inline","group"=&gt;JS_THEME,"weight"=&gt;20));
  }
}

function mymodule_submit_ga($form,&amp;$form_state) {
  //set temporary variable for the code above
  $_SESSION['mymodule_submission_successful'] = TRUE;
}


I'm sharing this in case it helps anybody, but as I'm not a PHP expert, I can't help the feeling that I missed something really simple.

Is there an easier way of doing this?
An easier method (that requires no coding) would be to set the webform's "Redirection location" setting to "Custom URL" and enter 'node/%nid?f=my_webform_success'.

This will post the form to itself and also allow you to add some unique key/value to the URL.

Then within Google Analytics you can set a Goal with the Goal URL set to 'f=my_webform_success' and the Match Type set to "Regular Expression Match".