Sub topic 3
Page views and browser history changes in single-page sites
This chapter covers how GA4 records page views on sites that change the URL without reloading the page. It assumes you have a GA4 web data stream with the Google tag installed (gtag.js or Google Tag Manager), you know how events and parameters work, and you can find your way around the Admin interface. The code examples use basic HTML and JavaScript.
Why page views need special handling
On a traditional site, every navigation loads a new document. The Google tag initializes on each load and sends a page_view event. This is the baseline behavior, and you can't switch it off from the enhanced measurement settings.
A single-page application (SPA) works differently. The browser loads one HTML document, and JavaScript swaps the visible content and updates the address bar. The tag initializes once, so with no extra help GA4 would see one page view per visit, whatever the user actually looked at.
The browser exposes the URL changes through the History API. The relevant pieces are:
history.pushState()adds a new entry to the history and changes the URL.history.replaceState()changes the URL of the current entry without adding one.- The
popstateevent fires when the user moves through history with the back or forward buttons.
Enhanced measurement has an option that watches for these changes and sends a page_view event for each one.
Where the setting lives
Page views is the first item in the enhanced measurement list. Its toggle is always on. The extra behavior sits behind the gear icon:
- Go to Admin > Data collection and modification > Data streams and select your web stream.
- Under Enhanced measurement, click the gear icon.
- Next to Page views, expand Show advanced settings.
- Switch Page changes based on browser history events on or off.
New web streams usually have this option on. Check it on older streams, because the setting is per stream.
What GA4 sends
When the tag detects a qualifying history change, it sends a page_view event. It is the same event name as a normal page load, so reports don't need to distinguish the two. The parameters are:
| Parameter | Meaning | Value on a history change |
|---|---|---|
| `page_location` | The full URL of the page | The new URL, after the change |
| `page_referrer` | The URL of the previous page | The URL the user was on before the change |
| `page_title` | The document title | Whatever `document.title` holds when the event is sent |
| `engagement_time_msec` | Time the page was in the foreground | Time spent on the previous view |
Three details matter in practice.
First, the referrer is internal. On a virtual page view, page_referrer is the previous page on your own site, not the external site that brought the user. Session source and medium stay with the session, so traffic attribution doesn't change.
Second, a history change doesn't start a new session. The session continues, and each virtual page view adds to the session's event count and engagement time.
Third, the title can be stale. Many routers call pushState first and update document.title afterward. The tag may read the title in between and send the previous page's title with the new URL. The fix is to set the title before calling pushState.
The flow of a virtual page view
The diagram shows what happens when a user clicks an in-app link.
A minimal working example
This page has two views and a link between them. It loads the tag with debug_mode on so you can watch the events in DebugView. Replace G-XXXXXXXXXX with your measurement ID.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Home</title>
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXXXX', { debug_mode: true });
</script>
</head>
<body>
<nav>
<a href="/" data-route>Home</a>
<a href="/pricing" data-route>Pricing</a>
</nav>
<main id="view">Home view</main>
<script>
const titles = { '/': 'Home', '/pricing': 'Pricing' };
const views = { '/': 'Home view', '/pricing': 'Pricing view' };
function render(path) {
document.title = titles[path] || 'Not found';
document.getElementById('view').textContent = views[path] || 'Not found';
}
document.querySelectorAll('a[data-route]').forEach((link) => {
link.addEventListener('click', (event) => {
event.preventDefault();
const path = new URL(link.href).pathname;
render(path); // sets the title first
history.pushState({}, '', path); // then changes the URL
});
});
window.addEventListener('popstate', () => render(location.pathname));
</script>
</body>
</html>Serve it from a local server that returns this page for every path, such as /pricing. Otherwise a reload on /pricing returns a 404. Click Pricing, then use the browser's back button. In DebugView you should see a page_view for the pricing URL, then another for the home URL. The title is already updated in each, because render() runs before pushState.
What counts as a change
The listener reacts to URL changes made through the History API, including back and forward navigation. Behavior to expect:
| Action | Typically sends `page_view`? | Notes |
|---|---|---|
| Full page load | Yes | The normal page view, regardless of this setting |
| `history.pushState()` to a new URL | Yes | The main SPA case |
| `history.replaceState()` to a new URL | Yes | Used by routers for redirects and query updates |
| Back or forward (`popstate`) | Yes | Each step sends a view |
| Change of the `#fragment` only | Yes, commonly | Anchor links on one long page can look like new pages |
| Calling `pushState` with the same URL | No new URL | Nothing meaningful changed |
Fragment changes need care. A long page with a table of contents that uses #section links can produce a page_view for each click, which inflates view counts and splits Pages and screens data by fragment. Check this in DebugView on your own site before trusting the numbers. If your site is not an SPA and relies on anchors, turning the history option off is usually the right choice.
Also be aware of replaceState calls you didn't write. Some libraries rewrite the query string with replaceState (for filters, tabs, or tracking parameters). Each rewrite that changes the URL can send a page_view.
Duplicate page views
The most common SPA mistake is counting each view twice. It happens when two mechanisms report the same navigation.
- Enhanced measurement history detection is on, and your code also sends
page_viewmanually on each route change. - You use Google Tag Manager with a History Change trigger firing a GA4 event tag named
page_view, and the history option is also on in the stream. - The router calls both
pushStateandreplaceStatefor one navigation, and each one sends a view.
Choose one source of virtual page views. If you want to control them yourself, turn the history option off in the stream and send the events from code. Disable the automatic page view on config so the first load isn't counted twice:
gtag('config', 'G-XXXXXXXXXX', { send_page_view: false });
function trackVirtualPageView(path, title) {
document.title = title;
gtag('event', 'page_view', {
page_location: location.origin + path,
page_title: title
});
}
// Call this from your router after each route change,
// and once on the initial load.
trackVirtualPageView(location.pathname, document.title);Remember that with send_page_view: false you must send the initial page view yourself, as the last line does.
Checking your work
Use these checks after any change to the setting or the router:
- Open DebugView (Admin > DebugView) with
debug_modeenabled, or open Tag Assistant preview for a GTM setup. - Navigate through three or four views, including a back-button step.
- Confirm there is exactly one
page_viewper navigation. - Open each event and check that
page_locationis the new URL,page_referreris the previous URL, andpage_titlematches the new view.
Later, in Reports > Engagement > Pages and screens, the page path and title dimensions will reflect these virtual views. Remember that standard reports can lag by a day or more, so DebugView is the right place for immediate verification.
Limitations to keep in mind
- The setting only watches the History API. Apps that swap content with no URL change, such as modals, tabs, or checkout steps held in state, produce no
page_view. They need custom events with a clear name and parameters. - Titles can lag, as described above. Fix them in the router, not in reports.
- The history setting is not configurable per route. If some URL changes are noise (filters, sort order), the stream-level option can't exclude them. In that case, turn it off and send views yourself for the routes that matter.
- Changing the setting affects only future data. It isn't applied retroactively.
Exercise
A React site has "Page changes based on browser history events" turned on. Developers also added code that calls gtag('event', 'page_view') after every route change. Reports show roughly twice as many page views as the server logs suggest. What is the cause, and what are two ways to fix it?
Show answer
Each route change is reported twice: once by the enhanced measurement history listener and once by the manual gtag call. Fix it by either (1) removing the manual call and relying on the history setting, or (2) turning off the history option in the data stream, setting sendpageview to false in the config, and sending all page views from code, including the initial load.
Exercise
After enabling history-based page changes, DebugView shows the correct pagelocation for each virtual view, but every pageview carries the title of the previous view. Why does this happen, and how do you fix it?
Show answer
The router calls history.pushState before it updates document.title, so the tag reads the old title when it detects the URL change. Update document.title before calling pushState (or otherwise ensure the title is set before the URL changes).
Exercise
A marketing site is not an SPA, but it has long pages with "#section" anchor links. Page view counts have jumped since the history setting was on. What should you check and what would you probably change?
Show answer
Check in DebugView whether clicking an anchor link sends a page_view with a fragment URL. If it does, the history listener is counting fragment changes as pages. Since the site is not an SPA and every real navigation is a full page load, turn off "Page changes based on browser history events" in the stream's advanced page view settings.