1

I'm trying to track some link clicks on a website that is using Craft CMS. I only have access to the Website and the Data Studio Report, but I don't have access to Google Analytics, GTM or any "deeper" level of the Control Panel. Thus, I thought I'd try to send the events directly to Analytics. Google has this How-To on their site, for which I need to implement the following script (beside an onclick event which is no problem):

<script>
/**
* Function that captures a click on an outbound link in Analytics.
* This function takes a valid URL string as an argument, and uses that URL string
* as the event label. Setting the transport method to 'beacon' lets the hit be sent
* using 'navigator.sendBeacon' in browser that support it.
*/
var captureOutboundLink = function(url) {
   ga('send', 'event', 'outbound', 'click', url, {
     'transport': 'beacon',
     'hitCallback': function(){document.location = url;}
   });
}
</script>

Unfortunately I got basically no idea about JavaScript or Twig and every time I try to include the code, it simply gets deleted. I guess it's because I need to transform the script into Twig - but I got no idea how to do this. My colleagues can't help me either, as they have even less of a programming understand than I do.

Can anyone help me out how to add this script?

1 Answer 1

1

You can add JS code to your twig template via JS tag, for example

templates/basic-layout.twig:

{% js %}
     ga('send', 'event', 'outbound', 'click', url, {
     'transport': 'beacon',
     'hitCallback': function(){document.location = url;}
   });
{% endjs %}

Or you can use {% block %} tag, e.g. somewhere in the footer

    {% block footerJs %}{% endblock %}
  </body>
</html>

And call it in the necessary template:

templates/example-section/entry.twig:

{% extends "basic_layout.twig" %}
{# ... some your code here ..#}
    {% block footerJs %}
             ga('send', 'event', 'outbound', 'click', url, {
             'transport': 'beacon',
             'hitCallback': function(){document.location = url;}
           });
    {% endblock %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.