How to setup Matomo (formerly Piwik) to track page views correctly.
-
Hi all!
I am using matomo together with laytheme. And as you know, laytheme builds javascript single page application, the page visits are hardly to track. Luckily after a long search I found a code snippet, that helped to get this functionality and I want to share it to those, who are struggling also. Inserting it into the head section will get the page view tracking running.Cheers!
Sebastian<!-- Matomo --> <script type="text/javascript"> // Custom locationchange event history.pushState = ( f => function pushState(){ var ret = f.apply(this, arguments); window.dispatchEvent(new Event('pushstate')); window.dispatchEvent(new Event('locationchange')); return ret; })(history.pushState); history.replaceState = ( f => function replaceState(){ var ret = f.apply(this, arguments); window.dispatchEvent(new Event('replacestate')); window.dispatchEvent(new Event('locationchange')); return ret; })(history.replaceState); window.addEventListener('popstate',()=>{ window.dispatchEvent(new Event('locationchange')) }); var _paq = window._paq || []; _paq.push(['trackPageView']); _paq.push(['enableLinkTracking']); (function() { var u="//{$PIWIK_URL}/"; _paq.push(['setTrackerUrl', u+'matomo.php']); _paq.push(['setSiteId', {$IDSITE}]); var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s); })(); // Single Page Application Tracking var formerUrl = location.href; window.addEventListener('locationchange', function() { _paq.push(['setReferrerUrl', formerUrl]); _paq.push(['setCustomUrl', location.href]); //_paq.push(['setDocumentTitle', document.title]); // remove all previously assigned custom variables, requires Matomo (formerly Piwik) 3.0.2 _paq.push(['deleteCustomVariables', 'page']); _paq.push(['setGenerationTimeMs', 0]); _paq.push(['trackPageView']); }); </script> <!-- End Matomo Code --> -
Dear @neunzehnachtneun
thank you @neunzehnachtneun for sharing!We see how we can use this in the future.
Best!
Marius
Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better 💗
Register Login