posthog-js icon indicating copy to clipboard operation
posthog-js copied to clipboard

Option to automatically track $pageleave and $pageview for SPAs

Open fluidsonic opened this issue 3 years ago • 2 comments
trafficstars

We have to add our own logic for tracking page changes due to history API. It would be nice to have this automated by PostHog, just as Google Analytics does.

Our implementation:

let isNavigating = false
let lastLocation = {...window.location}

window.addEventListener('popstate', function() {
    if (!isNavigating && lastLocation.href !== location.href) {
        posthog.capture('$pageleave', {
            $current_url: lastLocation.href,
            $host: lastLocation.host,
            $pathname: lastLocation.pathname,
        })
        posthog.capture('$pageview')
    }

    lastLocation = {...window.location}
})

function wrap(fn) {
    return function (state, _, url) {
        const isTracked = !isNavigating && url && url !== location.href
        if (isTracked) {
            isNavigating = true
            posthog.capture('$pageleave')
        }
        fn.apply(this, arguments)
        if (isTracked) {
            setTimeout(function() {
                posthog.capture('$pageview')
                lastLocation = {...window.location}
                isNavigating = false
            }, 50)
        }
    }
}

history.pushState = wrap(history.pushState)
history.replaceState = wrap(history.replaceState)

We have a timeout of 50ms to avoid tracking redirects (e.g. / -> /authenticated-only -> /sign-in?next=/authenticated-only - skip middle part).

fluidsonic avatar Apr 17 '22 18:04 fluidsonic

This should also stop tracking document.referrer after the first pushState or replaceState. It would report the initial referrer for all subsequent $pageview events which is incorrect. Either it should use the URL of the previous location or not include the referrer at all after the first $pageview event.

fluidsonic avatar Apr 21 '22 02:04 fluidsonic

This issue hasn't seen activity in two years! If you want to keep it open, post a comment or remove the stale label – otherwise this will be closed in two weeks.

posthog-bot avatar Apr 22 '24 09:04 posthog-bot

This issue was closed due to lack of activity. Feel free to reopen if it's still relevant.

posthog-bot avatar May 07 '24 09:05 posthog-bot