How to add query parameter before #stq= fragment

analytics
jquery

#1

Google Analytics doesn’t track HTML fragments (the portion of the url after the #). However the Swiftype search url looks like www.example.org/search/#stq=test&stp=1.

The Google Analytics tutorial here: https://swiftype.com/documentation/tutorials/ga says to use the stq query parameter. Is this out of date since the stq is a fragment instead of a query parameter?

How can I add the search query parameter so that it can be tracked? Something like:
www.example.org/search/?stq=test#stq=test&stp=1 should do the trick, however Swiftype strips all query parameters out of the search url.


Problems with Google Analytics Site Search Tracking
#2

Hey there,

Great question, and thank you for pointing out that the GA tutorial could use a refresh for clarity. :slight_smile:

With your Google Analytics tracking code installed on your site and when using the WordPress plug-in or the standard JavaScript embed code snippet provided in the Dashboard, capturing and passing the query parameter to GA will function without the need for any additional intervention.

If you’re using our client libraries to implement your Site Search experience, you’ll need to pass along a virtual page view to Google Analytics. They’ve some additional documentation here:

https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications

Also, here’s a sample of some JavaScript that you can use as a starting point to parse, convert, and pass that parameter along properly:

var url = window.location.href;
var re = new RegExp("\#stq=(.+)");
var m = url.match(re);


if (m != null) {
    var track = "/search?stq=" + m[1];
    ga('send', 'pageview', track);
} else {
    ga('send', 'pageview');
}

For the above, modify the regex for the re variable as needed, as well as the root path structure for the track variable.

I hope this helps!

NOTE: The above methods and conditions do not apply to GA tracking that is being implemented via Google Tag Manager.


Do I need to add the Swiftype install code for Google Analytics?
#3

Hi All, Another option which would not require coding is to read the fragment in Google Tag Manager and then either append it to the pageview URL and/or create a custom event to track the search query.