Embedding tracking js in a function

Good day everyone,

I am trying to setup matomo tracker with my consent banner: when the consent is given, the tracking code is executed and the user is tracked immediately so I don’t lose people who only connect to one page.

To do so, I use js injector on drupal/ Here’s my js code:

function matomo() {
    var _paq = window._paq || [];
    _paq.push(["trackPageView"]);
    _paq.push(["enableLinkTracking"]);
    (function () {
      var u = "https://analytics.com/";
      _paq.push(["setTrackerUrl", u + "matomo.php"]);
      _paq.push(["setSiteId", "3"]);
      var d = document,
        g = d.createElement("script"),
        s = d.getElementsByTagName("script")[0];
      g.type = "text/javascript";
      g.async = true;
      g.defer = true;
      g.src = u + "matomo.js";
      s.parentNode.insertBefore(g, s);
    })();
}
function awaitCookieValidation() {
    const agreed = document.cookie.valueOf("cookie-agreed");
    if (
      agreed.startsWith("cookie-agreed=1") ||
      agreed.startsWith("cookie-agreed=2")
    ) {
        matomo();
    } else {
      awaitCookieValidation();
    }
}
awaitCookieValidation();

However I have a problem: the js is loaded by the client but I never see any request to my matomo.php.
Moreover, no cookie is given to the user.

If I only user the js code without all the functions, I am correctly tracked.

Can you tell if I’m not doing something right ?

Thank you !

Hi,

The _paq variable needs to be a global variable for the matomo.js script to work properly.
As you put the tracking code in a function, it only exists inside that function.
You can work around that by adding window._paq=_paq below the var _paq = window._paq || []; line.