Automatic SPA pageview tracking

To track page views in a Single Page Application (SPA), you normally listen for route changes on your router and send a tracking call.

Here's how you can do it automatically, without changing any code in your application, by detecting when the URL changes:

Automatically track pageviews on a Single Page Application

```html
<script>
    (() => {
        let lastTrackedUrl = window.location.href;

        // Whenever 
        const trackPageView= () => {
            const currentUrl = window.location.href;
            if (currentUrl === lastTrackedUrl) return;
            
            // Page changed
            UST.trackNewPage();
            lastTrackedUrl = currentUrl;
        };

        // Monitor URL changes (pushState, replaceState, and popstate)
        ['pushState', 'replaceState'].forEach((method) => {
            const original = history[method];
            history[method] = function (...args) {
                const result = original.apply(this, args);
                try {
                    trackPageView();
                } catch (e) {
                    console.error(e);
                }
                return result;
            };
        });

        window.addEventListener('popstate', trackPageView);
    })();
</script>
```

Last updated