#define function in <head> and execute in script, Vanilla JS

1 messages ยท Page 1 of 1 (latest)

red flax
#

Hi, I am using google analytics, it sets up a function in the common layout -> head, then I need to set up another function which uses the first one, then I need to invoke the last function on button click.

Even though the function is defined in the head, when I try to call it from a script tag set up with an event listener, it doesn't have access to what's in the head.

This must be very basic, I highly appreciate any advice ๐Ÿ™๐Ÿป

light spindle
red flax
#

๐Ÿ™๐Ÿป Thank you!

Should I be using document.addEventListener('astro:page-load') to re initialize gtag("config") on every page?
My guess is yes, though it seems to make gtag non-accessible from the gtag_report function.

<!-- Google tag (gtag.js) -->
    <script src="https://www.googletagmanager.com/gtag/js?id=AW-ID"
    ></script>
    <script is:inline>
      window.dataLayer = window.dataLayer || [];
      function gtag() {
        dataLayer.push(arguments);
      }

      // Should this re-run on every page navigation via event listeners?
      gtag("js", new Date());
      gtag("config", "AW-ID");

      // This function tracks conversions and is separate.
      function gtag_report_conversion(url) {
        var callback = function () {
          if (typeof url != "undefined") {
            window.location = url;
          }
        };
        gtag("event", "conversion", {
          send_to: "AW-ID/-ID",
          event_callback: callback,
        });
        return false;
      }
    </script>
light spindle
#

Sorry, I missed your message.

#

You wouldn't have to if you preserve the script tag using transition:persist

red flax
#

Hmmmm I have returned.... This was working, but now because I need to implement cookie consent verification, I need to populate the gtag_report_conversion only once a user consents to cookies.
Setting up the gtag looks like it's working... But setting up the gtag_report_conversion function is not working, it's not available when I want to register a conversion, when a user clicks a certain button.