How to add a Google Analytics (GA4) tag or other Javascript snippet code using Grav Admin

I recently started using Grav for a separate blog unrelated to this one.  It's been great so far, with an easier learning curve than other self-hosted CMSes (though not easier than a default Blogger/Blogspot or Wordpress site).  One thing that was strange to me was that there doesn't seem to be a default way to add a piece of JS code such as a Google Analytics tag to your Grav site using the Admin console.

It's not readily apparent, but there are some plug-ins you can install such as "Custom JS", which I prefer to the Google Analytics plug-ins for future proofing and ease of adding other JS code snippets as needed.

From the Grav Admin console, go to Plugins > + Add > (search for "custom" in the filter box) and then install it.  Note, the plug-in automatically has a <script> tag before and </script> tag after. So if you are adding a code snippet that already starts with <script> and ends with </script> then you will need to remove them.  In the case of Google Analytics, it's doing a <script src=...> so you will need to add a closing </script> to start and a matching <script> at the end to account for what the plug-in is adding.  Paste your JS code into the Inline Javascript text area and save.














Example of the code you would add (note the closing tag at the top and the opening tag at the bottom, to account for what the plug-in is adding behind-the-scenes):

</script>

<!-- Google tag (gtag.js) -->

<script async src="https://www.googletagmanager.com/gtag/js?id=G-ABC12345"></script>

<script>

  window.dataLayer = window.dataLayer || [];

  function gtag(){dataLayer.push(arguments);}

  gtag('js', new Date());


  gtag('config', 'G-ABC12345');

</script>

<script>


Screenshot showing the Google plug-ins that may or may not work better for you.  But I like Custom JS for more flexibility in case I need to add other JS code.



Comments

Popular posts from this blog

Domain registrar pricing comparison (2014)

How to block the Admiral anti ad-block detection message

usoclient.exe in Windows 10 wakes up my PC with Wake Source: Unknown