Exit Dwell Time Tracking via sendBeacon & Visibility API
Asynchronous Exit Telemetry via navigator.sendBeacon and Visibility State
Executive Architectural Takeaway: Web analytics pipelines historically fail to record session duration on single-page sessions and terminal exit pages because traditional duration calculation relies on timestamp deltas between consecutive hits. By implementing asynchronous egress beacons via navigator.sendBeacon coupled to the visibilitychange API instead of synchronous unload listeners, engineering teams capture true dwell time while preserving browser bfcache compatibility and eliminating main-thread blocking.
Legacy tracking implementations historically attempted to capture exit engagement by attaching event listeners to window.beforeunload or window.unload. In these patterns, developers triggered synchronous XMLHttpRequest calls or looped empty while conditions to force the browser engine to hold the network stack open until the analytics ping completed. This architecture directly degrades user experience by freezing page dismissal, causes severe mobile browser drop-offs when operating systems terminate headless network threads, and breaks modern browser navigation optimizations.
The modern standard utilizes navigator.sendBeacon, an API engineered specifically to transmit small amounts of data (typically under 64KB) over HTTP POST asynchronously to an ingestion server. The execution lifecycle of sendBeacon is managed directly by the browser's networking process rather than the document execution context. Consequently, requests successfully dispatch even after document execution terminates, providing an optimal primitive for logging exit metrics, engagement duration, and final interaction states.
Technical SEO, bfcache Compatibility, and Core Web Vitals Preservation
Attaching listeners to unload or invoking blocking operations during beforeunload destroys eligibility for the Back/Forward Cache (bfcache). The bfcache is an in-memory snapshot mechanism that enables instantaneous back and forward navigations. When a page registers an unload listener, browsers such as Chrome, Safari, and Firefox drop the page from cache eligibility. For sites relying on programmatic SEO and deep organic content discovery paths, loss of bfcache access directly increases subsequent page load latencies, inflating Largest Contentful Paint (LCP) and Interaction to Next Paint (INP) metrics across returning sessions.
Search bots and synthetic performance monitors penalize pages that incur long main-thread tasks during page transitions. Headless browser crawls (such as Googlebot rendering cycles using modern Chrome engines) evaluate cumulative JavaScript execution cost. When legacy scripts fire blocking network requests during page unload, the browser runtime registers extended Long Tasks (> 50ms), degrading overall page quality signals.
Migrating terminal telemetry to the Page Visibility API resolves these performance bottlenecks:
- bfcache Restoration: Replacing
unloadwithvisibilitychangeallows the browser to freeze and restore the document in memory without process termination. - Reliable Dispatch:
document.visibilityState === 'hidden'fires consistently across all platforms, including mobile viewports where users switch apps or background the browser without triggering DOM unload events. - Zero Thread Starvation: Beacons execute on independent browser networking threads, yielding 0ms main-thread blockage during critical navigation paths.
Marketing Ops Implementation: Production Runbook & Pipeline Engineering
To capture true engagement time and exit interactions, implement an active dwell timer that monitors visibilitychange state transitions. The client-side telemetry script measures active viewing time (pausing when the document is hidden) and pushes an egress payload via navigator.sendBeacon to a Server-Side Google Tag Manager (sGTM) endpoint or custom Cloudflare Worker.
// client-dwell-tracker.ts
interface EngagementPayload {
clientId: string;
sessionDurationMs: number;
activeEngagementMs: number;
path: string;
scrollDepthMax: number;
}
class ExitTelemetryEngine {
private startTime: number = performance.now();
private activeTime: number = 0;
private lastActiveTimestamp: number = performance.now();
private maxScroll: number = 0;
private beaconEndpoint: string;
constructor(endpoint: string) {
this.beaconEndpoint = endpoint;
this.initListeners();
}
private initListeners(): void {
window.addEventListener('scroll', () => {
const depth = Math.round(
((window.scrollY + window.innerHeight) / document.documentElement.scrollHeight) * 100
);
if (depth > this.maxScroll) this.maxScroll = depth;
}, { passive: true });
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
this.calculateActiveTime();
this.dispatchBeacon();
} else {
this.lastActiveTimestamp = performance.now();
}
});
}
private calculateActiveTime(): void {
const now = performance.now();
this.activeTime += (now - this.lastActiveTimestamp);
this.lastActiveTimestamp = now;
}
private dispatchBeacon(): void {
const payload: EngagementPayload = {
clientId: window.crypto.randomUUID(),
sessionDurationMs: Math.round(performance.now() - this.startTime),
activeEngagementMs: Math.round(this.activeTime),
path: window.location.pathname,
scrollDepthMax: this.maxScroll,
};
const blob = new Blob([JSON.stringify(payload)], { type: 'application/json' });
navigator.sendBeacon(this.beaconEndpoint, blob);
}
}
new ExitTelemetryEngine('https://collect.internal-analytics.domain/v1/egress');
Once the beacon arrives at your edge proxy, route the raw JSON payloads into BigQuery via Pub/Sub and Cloud Run. Use the following partition-optimized SQL model to reconcile exit dwell times with standard analytics sessions and determine true bounce vs deep-read engagement.
-- bigquery_exit_session_reconciliation.sql
WITH raw_egress AS (
SELECT
clientId,
path,
activeEngagementMs / 1000.0 AS active_seconds,
scrollDepthMax,
TIMESTAMP_TRUNC(_PARTITIONTIME, DAY) AS partition_date,
ROW_NUMBER() OVER (PARTITION BY clientId, path ORDER BY activeEngagementMs DESC) as rank_latest
FROM `analytics_warehouse.exit_telemetry_events`
WHERE _PARTITIONTIME >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY)
)
SELECT
path,
COUNT(DISTINCT clientId) AS total_terminal_sessions,
ROUND(AVG(active_seconds), 2) AS mean_active_dwell_seconds,
ROUND(APPROX_QUANTILES(active_seconds, 100)[OFFSET(50)], 2) AS median_dwell_seconds,
ROUND(AVG(scrollDepthMax), 1) AS mean_scroll_depth,
COUNTIF(active_seconds > 45 AND scrollDepthMax >= 60) AS qualified_content_reads,
SAFE_DIVIDE(
COUNTIF(active_seconds > 45 AND scrollDepthMax >= 60),
COUNT(DISTINCT clientId)
) * 100.0 AS true_content_efficiency_pct
FROM raw_egress
WHERE rank_latest = 1
GROUP BY path
HAVING total_terminal_sessions > 100
ORDER BY total_terminal_sessions DESC;
Enterprise Pipeline Hygiene, CAC Reduction, and High-Intent B2B Lead Scoring
In enterprise B2B funnels, terminal page telemetry fundamentally alters account-based marketing (ABM) intent scoring. High-value assets—such as comprehensive documentation, security compliance pages (SOC 2 summaries), and transparent enterprise pricing models—consistently surface as terminal exit nodes. Under legacy Google Analytics attribution modeling, an enterprise buyer who arrives via organic search, reads an un-gated security guide for six minutes, and leaves without a subsequent pageview is classified as an immediate 0-second bounce. This algorithmic blind spot misattributes paid and organic CAC, signaling to growth teams that campaigns are driving unqualified traffic.
Capturing true active engagement via navigator.sendBeacon isolates high-intent prospects by registering active reading sessions exceeding 60 seconds with significant scroll depth. These signals are piped directly to reverse-ETL platforms (such as Hightouch or Census) to enrich CRM records in HubSpot or Salesforce. RevOps teams can trigger targeted outbound cadences when accounts achieve high active-time thresholds on critical product documentation, shrinking sales cycles without forcing leads behind conversion-killing content gates.
System Telemetry Source: Original Engineering Report
Related Growth Blueprints
All Playbooks →Want this working inside your business?
Whether you're a founder fixing tracking leaks or a team scaling SEO and AI workflows, share your site and bottleneck for a clear diagnostic within 48 hours.