Zlatan Omerovic
Zlatan Omerovic

Reputation: 4097

History state pushing and Google Analytics

I'm having a problem with tracking my website via history.state/pushing. I have this Google Analytics code:

<script type="text/javascript">
    (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');

    ga('create', 'UA-XXXXXXXX-X', 'auto');
    ga('send', 'pageview');
</script>

Now I have the event listener to check when history.pushState occours:

<script>
(function(history){
    var pushState = history.pushState;
    history.pushState = function(state) {
        if (typeof history.onpushstate == "function") {
            history.onpushstate({state: state});
        }
        // ... whatever else you want to do
        // maybe call onhashchange e.handler
        return pushState.apply(history, arguments);
    }
})(window.history);

function __inArray(needle, haystack) {
    var length = haystack.length;

    for(var i = 0; i < length; i++) {
        if(haystack[i] == needle) return true;
    }

    return false;
}

window.onpopstate = history.onpushstate = function(e) {
    setTimeout(function() {
        var path = document.location.pathname;

        ga('set', path);
        ga('send', 'pageview');
    }, 650);
}
</script>

Tracks good and it sends the appopriate URL's where it should, but the Chrome extension Tag Assistant (by Google) reports me:

Same web property ID is tracked twice.

And the second instance of my Google Analytics tracking code appears in the list, in the Tag Assistant.

What's wrong with my implementation and/or approach?


Edit:

I have like four URL's:

/home
/home/personal-info
/home/employment-info
/home/privacy-settings
/home/documents

And I don't want /home tracked.

Upvotes: 0

Views: 1885

Answers (2)

Frank Kieviet
Frank Kieviet

Reputation: 36

Tag Assistant Recordings reports a warning that a page is tracked twice if the page sends more than one pageview hit in a short time period.

(Tag Assistant Recordings currently does not consider the parameters of the pageview, and that's something that probably should change in Tag Assistant)

In this case you have a pageview hit in the initialization of the page, and one in the event handler.

Upvotes: 2

antishok
antishok

Reputation: 2910

You're not setting the path correctly. Should be ga('set', 'page', path) or you can just do ga('send', 'pageview', path)

Upvotes: 1

Related Questions