Captain Kirk
Captain Kirk

Reputation: 1216

How can a parameter value from a URL be inserted as a variable in a Google Analytics code?

I have the following url:

domain.com/product/page.html?user_is=234

And using JavaScript, I am picking up the variable value in the 'user' parameter:

  var urlParams = new URLSearchParams(window.location.search);
  var user_value = urlParams.get('user_is');

And GA code that looks like this in the target button I am looking to target:

<button class="code" onclick="gtag('event', 'click', {eventCategory: 'Yes Code',eventAction: 'click',eventLabel: 'user_value'});">

What I am struggling with is getting the value in 'user_value' to be rendered in the GA code so I can track a specific user's click. It appears I cannot render this variable using JavaScript. What are my options?

Upvotes: 1

Views: 47

Answers (1)

Code Maniac
Code Maniac

Reputation: 37775

Instead of calling gtag function inline you can create a helper function to get value and assign it to user_value and then call gtag

<button class="code" onclick="handleGtag()">

Function

function handleGtag(){
 var urlParams = new URLSearchParams(window.location.search);
 var user_value = urlParams.get('user_is');
 gtag('event', 'click', {eventCategory: 'Yes Code',eventAction: 'click',eventLabel: user_value});
}

Upvotes: 2

Related Questions