ihucos / counter.dev

Web Analytics made simple
https://counter.dev
GNU Affero General Public License v3.0
927 stars 41 forks source link

How to correctly implement Counter.dev in a Vue.js Single Page Application? #120

Open saeedesmaili opened 1 year ago

saeedesmaili commented 1 year ago

I want to use Counter.dev to track page views on my Vue.js Single Page app. I've noticed that the current implementation of the tracking script doesn't correctly track page views when navigating between pages using components.

Could you please provide some guidance on how to correctly implement Counter.dev in a Vue.js SPA to ensure accurate page view tracking when the route changes?

I have added the tracking script to public/index.html's <head> section, and the counter is only counting the first page each user visits.

Thank you for your help and for developing Counter.dev

ihucos commented 1 year ago

Hello!

great question. I would like to support and properly document how to do this. As an old-school backend developer Single Page applications are magic to me. There is something called pushState that could make such an integration plug and play? I have to confess that I would like to support SPA but lack the knowledge to do it properly.

Cheers

digitalmio commented 1 month ago

I presume this should do the trick:

var stateListener = function(type) {
    var org = history[type];
    return function() {
        var rv = org.apply(this, arguments);
        var e = new Event(type);
        e.arguments = arguments;
        window.dispatchEvent(e);
        return rv;
    };
};
history.pushState = stateListener('pushState');
history.replaceState = stateListener('replaceState');

window.addEventListener('pushState', (e) => sendTrackingEvent());
window.addEventListener('replaceState', (e) => sendTrackingEvent());
});

I tested this long time ago on my analytics script that finally never released, but this was working fine. I've based this code on https://gist.github.com/rudiedirkx/fd568b08d7bffd6bd372