Quantcast
Channel: Support & Bugs - Matomo forums
Viewing all articles
Browse latest Browse all 5706

Need help integrating page view tracking into React SPA

$
0
0

@cbattleNTT wrote:

Hi,
I’m new to Matomo and I’m trying to integrate page view tracking into my single-page website in React, and I haven’t managed to get it to work. I’m following the guide here Single-Page Application Tracking: Integrate - Matomo Analytics (formerly Piwik Analytics) - Developer Docs - v3
but the hash change listening function isn’t working. I have the feeling I’m making some basic error, does anyone have advice on how to do this? My code looks like this:

    <script type="text/javascript">
        var _paq = window._paq || [];
        /* tracker methods like "setCustomDimension" should be called before "trackPageView" */
        _paq.push(["setDocumentTitle", document.domain + "/" + document.title]);
        _paq.push(["setCookieDomain", "*.<MY_WEBSITE>"]);
        _paq.push(['trackPageView']);
        _paq.push(['enableLinkTracking']);
        (function() {
        var u="https://<MY_WEBSITE>";
        _paq.push(['setTrackerUrl', u+'matomo.php']);
        _paq.push(['setSiteId', '<MY SITE ID>']);
        var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
        g.type='text/javascript'; g.async=true; g.defer=true; g.src='//<MY_WEBSITE>/matomo.js'; s.parentNode.insertBefore(g,s);
        })();

        var currentUrl = location.href;
        window.addEventListener('hashchange', function() {
            _paq.push(['setReferrerUrl', currentUrl]);
            currentUrl = '/' + window.location.hash.substr(1);
            _paq.push(['setCustomUrl', currentUrl]);
            _paq.push(['setDocumentTitle', 'My New Title']);
        });
    </script>
    <!-- End Matomo Code -->

I’ve pasted this before the head closing tag in index.html. I’ve seen some posts suggesting to add the following to my React router
_paq.push([‘setCustomUrl’, ‘/’ + window.location.hash.substr(1)]);
_paq.push([‘setDocumentTitle’, ‘My New Title’]);
_paq.push([‘trackPageView’]);

but it’s not clear to me how to do this. Can anyone show me an explicit example of how to do this?

Thanks!

Posts: 3

Participants: 2

Read full topic


Viewing all articles
Browse latest Browse all 5706

Trending Articles