Need help setting up single page web application

Hi all!
I am using Matomo to track a single page website. Following this guide I added this code into the head section. But unfortunately it doesn’t track new page views. Am I missing anything?

Thanks in advance!

<!-- Matomo -->
<script type="text/javascript">
  var _paq = window._paq || [];
  (function() {
    var u="";
    _paq.push(['setTrackerUrl', u+'matomo.php']);
    _paq.push(['setSiteId', 1]);
    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 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']);

      // remove all previously assigned custom variables, requires Matomo (formerly Piwik) 3.0.2
      _paq.push(['deleteCustomVariables', 'page']); 
      _paq.push(['setGenerationTimeMs', 0]);

      // make Matomo aware of newly added content
      var content = document.getElementById('content');
      _paq.push(['FormAnalytics::scanForForms', content]);
<!-- End Matomo Code -->

Well, I just solved this issue.
As my website is a one site java script page, but it doesn’t work hash anchors, the documentation doesn’t help.

in the far reaches of the internet I found these helpful snippets, which define a new event called locationchange.

  // 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.replaceState = ( f => function replaceState(){
      var ret = f.apply(this, arguments);
      window.dispatchEvent(new Event('replacestate'));
      window.dispatchEvent(new Event('locationchange'));
      return ret;

    window.dispatchEvent(new Event('locationchange'))
1 Like