posthog-js
posthog-js copied to clipboard
Option to automatically track $pageleave and $pageview for SPAs
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).
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.
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.
This issue was closed due to lack of activity. Feel free to reopen if it's still relevant.