Automatic SPA pageview tracking
Last updated
Was this helpful?
Last updated
Was this helpful?
Was this helpful?
Here's how you can do it automatically, without changing any code in your application, by detecting when the URL changes:
```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>
```