SPA support
In a single-page application the CMP must know about route changes to process new content and track sessions correctly.
Option 1: manual (recommended)
Call onRouteChange() from your router's route change handler:
// React Router
useEffect(() => {
OptSens.onRouteChange();
}, [location.pathname]);
// Vue Router
router.afterEach(() => {
OptSens.onRouteChange();
});
// Next.js (Pages Router)
Router.events.on('routeChangeComplete', () => {
OptSens.onRouteChange();
});
// Next.js (App Router), usePathname from 'next/navigation'
const pathname = usePathname();
useEffect(() => {
OptSens.onRouteChange();
}, [pathname]);
Option 2: automatic detection
Detects route changes automatically by patching history.pushState and
replaceState and listening for browser back and forward navigation:
OptSens.on('ready', function () {
OptSens.enableSpaAutoDetect();
});
What onRouteChange() does
- Re-scans the DOM for new
data-os-categoryelements - Fires the session beacon if the session cookie expired
- Pushes an
OptSensPageViewevent to the GTM dataLayer - Emits the
route_changeevent