为angularjs动态插入google标记管理器(gtag.js)跟踪id

e3bfsja2  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(444)

我需要为angularjs动态插入google标签管理器(gtag.js)。我管理一个多租户站点,其中每个租户的跟踪id都是唯一的。
我们以前是这样做的(使用google analytics-analytics.js的旧方法),如下所示:
index.html-

<script>
        (function (i, s, o, g, r, a, m) {
            i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
                (i[r].q = i[r].q || []).push(arguments)
            }, i[r].l = 1 * new Date(); a = s.createElement(o),
            m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
        })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
    </script>

app.controller.js-

function setupAnalytics() {
  var googleTagEnabled = $settings.checkTrue('Analytics/GoogleTagEnabled');
  var googleTag = $settings['Analytics/GoogleTag'];
  if (googleTagEnabled) {
    $window.ga('create', googleTag, 'auto');

    $rootScope.$on('$stateChangeSuccess', function (event) {
      $window.ga('send', 'pageview', $location.path());
    });
  }
}

如何使用新的gtag方法实现这一点?

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXXX-YY"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'UA-XXXXXXXXX-YY');
</script>
xlpyo6sf

xlpyo6sf1#

解决了。
卢克·鲍里斯的回答值得称赞:https://stackoverflow.com/a/66530446/1098620
结合chris anker的回答:https://stackoverflow.com/a/48124899/1098620
index.html

<!-- no code here. -->

app.controller.js

function setupAnalytics() {
  var googleTagEnabled = $settings.checkTrue('Analytics/GoogleTagEnabled');
  var googleTag = $settings['Analytics/GoogleTag'];
  if (googleTagEnabled) {       
    // Setting dataLayer & gtag to window because I'm using a custom code text field in a tag management system
    window.dataLayer = window.dataLayer || [];
    window.gtag =
    window.gtag ||
    function() {
        window.dataLayer.push(arguments);
    };
    window.gtag("js", new Date());
    window.gtag("config", googleTag);

    // Set initial gtag/js?id=<first ID> script to <head>
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.async = true;
    script.src = "//www.googletagmanager.com/gtag/js?id=" + googleTag;
    document.getElementsByTagName("head")[0].appendChild(script);

    $rootScope.$on('$stateChangeSuccess', function (event) {
        $window.gtag('config', googleTag, {'page_path': $location.path()});
        $window.gtag('event', 'page_view');
    });
  }
}

相关问题