Google Analytics Setting Up A PageView On Hash Change

折月煮酒 提交于 2019-12-21 17:12:01

问题


I'm trying to get a home page that has a bunch of content under Isotope

to show each hash change as a pageview in Google Analytics. Originally, I was going to do this as events, but it really should be pageviews.

So I setup the modified GA:

(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', {'allowAnchor': true});
ga('send', 'pageview', { 'page': location.pathname + location.search + location.hash});

In Google Analytics, I see the hash tag now if someone goes to a specific URL — example: http://www.example.com/#pet-health If they reload the page, I see that hash in GA, but not if they click on an Isotope "nav" link to get to it. If they click, I'm just seeing "/"

In the Isotope firing, what I have doesn't seem to be working:

//Sets up filtering on click of Isotope navigational elements 
    $('#isotopeFilters a, .subnav a, #isotopeContainer .isotopeNav a, .page-template-page-home-php #logo').click(function(){
        var selector = $(this).attr('data-filter');
        var prettyselector = selector.substr(1);
        ga('send', 'pageview', location.pathname+location.search+location.hash);

        location.hash = prettyselector;

        $('#isotopeFilters a, .subnav a').removeClass('active');
        $('a[class="' + prettyselector + '"]').addClass('active');

        $container.isotope({ 
            filter: selector,
            itemSelector: '.item',
            masonry: {
                columnWidth: 270
            },
            animationOptions: {
            duration: 750,
            easing: 'linear',
            queue: false,
        }
      });
      return false;
    });

I thought that this line in the click function would do the trick:

ga('send', 'pageview', location.pathname+location.search+location.hash);

Is my syntax incorrect or missing something?

//Fires Isotope functionality when hash/URL changes
    $(window).hashchange( function(){
        if(location.hash!=''){
            var hashfilter = '.' + location.hash.substr(1);
        }else{
            var hashfilter = '.home';
        }

        $container.isotope({
            filter: hashfilter,
            itemSelector: '.item',
            masonry: {
                columnWidth: 270
            },
            animationOptions: {
                duration: 750,
                easing: 'linear',
                queue: false,
           }
        });
        isotopeSubNav();
    });

    if(location.hash!=''){
        var hashfilter = '.' + location.hash.substr(1);
        ga('send', 'pageview', location.pathname+location.search+location.hash);
        $(hashfilter).addClass('active');
    }

That's using the same syntax, so I'm assuming if I fix one, copying the syntax to the hashchange function will get that recording as well.


回答1:


To change the page path that gets sent to GA, you would to just make a slight modification to your code:

ga('send', 'pageview', {'page': location.pathname+location.search+location.hash});

More information can be found here: https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced?hl=en#fieldObject




回答2:


Sending page in sending pageview call is not recommended by Google:

While technically the send command for pageview hits accepts an optional page field as the third parameter, passing the page field that way is not recommend when tracking single page applications. This is because fields passed via the send command are not set on the tracker—they apply to the current hit only. Not updating the tracker will cause problems if your application sends any non-pageview hits (e.g. events or social interactions), as those hits will be associated with whatever page value the tracker had when it was created.

Use:

ga('set', 'page', location.pathname+location.search+location.hash);
ga('send', 'pageview');

Google Analytics guide on tracking Single Page Applications.




回答3:


Here is a full code sample to track hash pageviews and changes in google analtyics:

(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', 'https://www.google-analytics.com/analytics.js', 'ga');

    ga('create', 'UA-XXXXXXXX-X', 'auto');
    ga('set', 'page', location.pathname+location.search+location.hash);
    ga('send', 'pageview');
    window.addEventListener("hashchange", function (event) {
        ga('set', 'page', location.pathname + location.search + location.hash);
        ga('send', 'pageview');
    })



回答4:


Currently Google Analytics configuration loads Google Tag Manager script and is using gtag function and not ga so for me, previous solutions throws errors because 'ga is not defined'. What i do is a modification of inital Google Analytics configuration script with:

<script async src="https://www.googletagmanager.com/gtag/js?id=YOUR-GA-ID"></script>
<script>
     window.dataLayer = window.dataLayer || [];
     function gtag() {
         dataLayer.push(arguments);
     }
     gtag('js', new Date());
     gtag('config', 'YOUR-GA-ID', {
         'page_path': location.pathname + location.hash
     });
 </script>

To send content changes when page does not reload or URL (and/or content) change without reloading javascript, you must include somewhere in your scripts this code:

window.addEventListener("hashchange", function (event) {
       gtag('event', 'pageview', {
         'page_path': location.pathname+location.search+location.hash
       });
});

You can take a look at https://developers.google.com/analytics/devguides/collection/gtagjs/sending-data

And at https://developers.google.com/gtagjs/reference/event



来源:https://stackoverflow.com/questions/32378607/google-analytics-setting-up-a-pageview-on-hash-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!