How to dynamically access URL parameters and use them in your Answers front-end

Hi community,

I thought I’d share a little trick that will allow you to access any URL parameters and re-use them in your Answers experience.

Background:
Sometimes, brands will want a URL parameter to be dynamically “passed through” an Answers experience. This code will allow clients to add any custom URL parameter(s) when they initially point to the Answers result page, and that same parameter to be appended to links in your Answers experience.

The JavaScript code is inspired by the first response in this post.

Step 1: Add JavaScript to read and parse the parameter from your URL

Add the following code to your layouts > headincludes.hbs file. By adding the script there you’re making it availble on every page of your experience.

<script>
  function getParameterByName(name, url = window.location.href) {
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
  }

  var [InternalParamName] = getParameterByName('[ExternalParamName ]');

</script>

Replace ExternalParamName with the name of the actual parameter and InternalParamName with an internal label that you will use to reference the parameter value within your config files.

If you’re targeting the parameter store, your file might look like this:

Step 2: Add parameter variable to your card

Add the parameter variable to your front-end files depending on where you need it. In my case, I want to append it to the title link of my product card:

This way, the title URLs going out of my Answers experience will include the parameter that was initially passed to the search result page, allowing the brand to close an important analytical loop.

Notes:

  • You can access multiple parameters by duplicating line 11 (in Step 1) and creating additional variables.
  • If the designated parameter is missing from the URL, it will still be appended where specified, just with a null value.

Any questions, feel free to reach out!

1 Like