Sam Lewis
Sam Lewis

Reputation: 542

Insert dynamically GA tracking ID code produce an error "No HTTP response detected" Google tag manager

I have several domains with and different tracking Ids - each domain has it's own tracking ID.

I'm using following directive to insert correct ID:

app.directive('analytics', ['$compile', function($compile) {
return {
    restrict: 'A',
    scope: {
        id: '=analytics'
    },
    link: function (scope) {
        var el =  $("#analytics");
        var text = "(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'); ";
        scope.$watch('id', function (trackId) {
            if (trackId) {
                $(el).append(text, "ga('create','" + trackId + "', 'auto');");
            }
            $compile(el)(scope);
        })
    }
};}]);

and <script id="analytics" type="text/javascript"></script> Sure, i can just create script tag and insert to the head, instead of using id.

I got an error Missing HTTP Response

Missing HTTP Response denotes that, while the Google Analytics code was detected in the page source, the script itself did not execute. Each time the Google Analytics script executes, we expect an HTTP Response carrying the tracking request to Google’s servers. This means that the Google Analytics code is not implemented properly on the page and no data will be collected.

If I manually add tracking id to index.html - no errors. But I still receive data in Google Analytics somehow, but receive following error message in Google Analytics:

No valid tracking code found for property. Make sure your pages are tagged with a supported version of the tracking code.

Is there any valid way to add tracking ID dynamically?

Upvotes: 0

Views: 1008

Answers (1)

J Brazier
J Brazier

Reputation: 884

Just use Google Tag Manager.

With Google Tag Manager you can set up a lookup variable that takes the {{Page Hostname}} variable and outputs the relevant tracking ID.

Here's an example that I've thrown together. Bear in mind that the hostname will be considered different if it's preceeded by 'www.', and the lookup table matches exact values only (although it also provides a default option, which you can use for debugging purposes).

When deploying your Page View tag using Google Tag Manager, just set the Tracking ID field equal to whatever you named your variable.

domain lookup variable

page view tag

Upvotes: 2

Related Questions