Response Page Customization Example: Analytics Event Tracking

Overview

This page documents a real, production custom-code implementation running on the response pages of one of our Enterprise customers: a client-side analytics integration that reports the end user's journey through the challenge (displayed, passed, failed, abandoned) to the customer's analytics platform, plus a few small UI adjustments. Identifying details have been genericized; the structure and the code patterns are the production ones.

It is written as an annotated implementation example: use it to understand how such a customization works, adapt it to your own analytics platform, or debug an event that did not arrive — without needing to involve DataDome Support for every question.

⚠️

Prerequisite reading

This page assumes you know the execution model of response-page custom code — the iframe sandbox, the three JavaScript sections, and the defensive coding rules. Read Response Page Custom JavaScript first; everything here follows those rules.

Architecture: detection vs delivery

The implementation is split across two of the JavaScript sections of the Advanced code tab (Management → Response Pages), with a deliberate separation of concerns:

LayerSectionRole
Tracker libraryHeader JSDetection. Watches the page (DOM observers, event listeners) and turns low-level signals into named journey events (slider_completed, block_page_loaded, …). Platform-agnostic: it knows nothing about where events are sent.
Delivery adapterBottom Body JSDelivery. Subscribes to the tracker's events, maps each one to the analytics platform's vocabulary, builds the beacon parameters, and sends the request. All platform-specific knowledge lives here.

The tracker owns detection; the adapter owns delivery. This is the recommended pattern for any analytics customization: when DataDome's page markup evolves, only the shared detection layer needs an update — your delivery logic and event vocabulary are untouched. Conversely, changing what you send (a new parameter, a renamed event) never touches the fragile DOM-watching code.

The Header JS defines a window.DDTracking global but does nothing on its own. Everything starts when the adapter calls DDTracking.init() once the DOM is ready:

DDTracking.init({
  samplingRate: 1, // 1 = every page load fires events; N = ~1/N of page loads
  onEvent: function (eventName, ctx) {
    // ctx = { pageType: 'captcha'|'hard_block'|'device_check',
    //         isAudioMode: boolean, requestId: string }
    // ... map the event and send the beacon (see below)
  }
});

The analytics beacon

For every detected event, the adapter sends a single GET request to the customer's collection endpoint:

https://analytics.example.com/collect?event_name=...&event_category=...

Routing by domain (multi-brand setups)

The same code can be deployed on the domains of several brands. When the destination differs per brand, derive it from the page's hostname:

function getBrand() {
  var host = _win.location.hostname || '';
  if (host.indexOf('brand-two') !== -1) { return 'brand-two'; }
  return 'brand-one';
}
var ENDPOINT = 'https://analytics.' + getBrand() + '.example/collect';

Remember that the response page is served from a DataDome-managed origin for your domain: location.hostname inside the challenge document reflects the protected domain being served, which is why this works.

How event_source is determined

event_source distinguishes web traffic from the mobile apps. The response page is the same in both cases — what differs is the container it is displayed in. The DataDome mobile SDKs (and React Native WebView) expose JavaScript bridges inside their webviews, so the adapter feature-detects those bridges:

function getEventSource() {
  var w = _win;
  // Android SDK webview: exposes window.android.onCaptchaSuccess
  var isAndroidSdk = !!(w.android && w.android.onCaptchaSuccess);
  // iOS SDK webview: exposes a webkit message handler
  var isIosSdk = !!(w.webkit && w.webkit.messageHandlers
                    && w.webkit.messageHandlers.onCaptchaSuccess);
  return (isAndroidSdk || isIosSdk || w.ReactNativeWebView) ? 'mobile' : 'web';
}

If an event arrives with event_source=web from what should be app traffic, the webview did not expose the SDK bridge — check the SDK integration on the app side before suspecting the response page.

Beacon parameters

ParameterValueSource
event_nameThe journey event, e.g. slider_completedDetection layer (see catalog below)
event_categoryThe platform-side category the event maps toThe adapter's EVENT_TYPES map
event_sourceweb or mobileSDK-bridge detection (see above)
request_idThe DataDome request ID of this challengeParsed by the tracker from the page ([data-dd-request-id]) — correlate it with DataDome dashboard traffic and server-side enriched headers
client_idThe DataDome client ID (window.ddm.cid)Read lazily at event time — ddm does not exist when the section first runs
event_timeISO 8601 timestampBuilt at send time
(fixed values)Constants identifying this integration to the analytics platformConstants in the adapter

Delivery is wrapped in try/catch and uses fetch(..., { keepalive: true, credentials: 'include' }) — keepalive lets close-time events (slider_closed, block_page_closed) survive the page unload, and a failed beacon must never break the challenge.

Event catalog

Each detected event is mapped to a platform-side category by the adapter — in this implementation, a plain object:

var EVENT_TYPES = {
  slider_loaded: 'impression',
  slider_completed: 'action',
  slider_failed: 'error'
  // ...one entry per event you want delivered
};

Events not present in the map are silently dropped — that is the on/off switch per event.

Slider page:

EventCategoryFires when
slider_loadedimpressionPage loaded — suppressed when arriving from a Device Check redirect or from a challenge reload, so one journey does not produce two load events
slider_completedactionThe puzzle is solved (the page's #analyticsCaptchaPassed marker flips)
slider_failederrorThe slider is positioned incorrectly (slider-error state appears)
slider_timeoutabandonThe retry state appears without a preceding failure (inactivity)
slider_reloadimpressionThe user clicks the reload button (visual mode)
slider_closedabandonThe page unloads (pagehide) with no completion, failure, or reload — an abandon
slider_contact_formactionThe feedback form is submitted

Audio verification (accessibility mode, same page):

EventCategoryFires when
audio_verification_loadedimpressionAudio mode activated — by click, or automatically restored from a previous visit
audio_verification_completedactionAudio answer correct
audio_verification_failederrorAudio answer wrong
audio_verification_reloadimpressionReload clicked while in audio mode

The tracker gates its slider and audio observers on the current mode: the underlying widget mutates both sets of DOM markers regardless of which mode is visible, so without that gating every audio answer would also emit a spurious slider event, and vice versa.

Block page:

EventCategoryFires when
block_page_loadedimpressionPage loaded (suppressed when arriving from a Device Check redirect)
block_page_contact_formactionThe feedback form is submitted (deduplicated)
block_page_closedabandonThe page unloads

Device Check outcomes (emitted on the destination page, not on the Device Check page itself):

EventCategoryFires when
device_check_redirect_to_sliderredirectA slider page loads carrying the Device Check origin marker (dm=dc_* in the URL) — replaces slider_loaded for that view
device_check_redirect_to_blockredirectA block page loads carrying the marker — replaces block_page_loaded

Coverage and known limitations

ScenarioEventsStatus
Web — challenge (slider) pageslider_loaded, then completion/failure/abandon events✅ Available
Mobile app webview — challenge pageSame events, with event_source=mobile✅ Available
Device Check displayed(none)⚠️ Known limitation — the Device Check page emits no tracking events today
Device Check → request allowed(none — no response page follows)⚠️ Not observable client-side; server-side signals (enriched headers) only
Device Check → Sliderdevice_check_redirect_to_slider✅ Available
Device Check → Blockdevice_check_redirect_to_block✅ Available

Adding a custom event on a specific action

Two situations, two mechanisms:

1. The tracker already detects it. Check the catalog above first. If the event exists but you do not receive it, it is probably absent from (or misspelled in) the adapter's EVENT_TYPES map — adding the entry is the whole change:

var EVENT_TYPES = {
  // ...existing entries...
  slider_reload: 'impression'   // ← start delivering an already-detected event
};

2. The action is not detected by the tracker. Attach your own listener in the Bottom Body JS and send the beacon through the same path. Example — tracking that a user switched to the audio challenge, as a distinct action event:

// Inside the same ready(...) callback, after DDTracking.init(...)
var audioBtn = _win.document.getElementById('captcha__audio__button');
if (audioBtn) {                              // null-check: the button only
  audioBtn.addEventListener('click', function () {  // exists on the slider page
    // Reuse the shared send path — same endpoint, same parameters —
    // so the custom event is indistinguishable from a built-in one downstream.
    sendBeacon('audio_mode_opened', 'action');
  });
}

For this to work, extract the beacon-building code from onEvent into a shared sendBeacon(eventName, eventCategory) function that both the adapter and your custom listeners call — instead of duplicating the parameter list.

Agree any new event_name with your analytics team before shipping it, so the receiving side expects it.

Do's and don'ts

Do

  • Keep the two layers separate. Detection changes go in the Header JS library; delivery changes go in the Bottom Body JS adapter.
  • Null-check every DOM lookup and length-check every collection before use — elements differ per page type, and lookups legitimately return nothing on the other pages.
  • Read DataDome globals lazily (window.ddm && window.ddm.cid at event time, never at load time) — they are populated after your code runs.
  • Wrap all delivery in try/catch and fail silently. A tracking outage must be invisible to the end user.
  • Test on a low-traffic domain first and keep the previous version of each field for instant rollback — see the test-domain procedure.
  • Keep every domain's configuration in sync when you change the shared logic. The configuration is stored per domain; a fix applied to one domain does not propagate to the others. Once validated, propagate it with Copy to Other Domains (select Header, Top body & Bottom body JS).

Don't

  • Don't redirect or open new tabs from the response page — the iframe sandbox blocks it silently.
  • Don't touch the Slider widget internals (the puzzle/slider) — it is a security surface, and it can change without notice.
  • Don't block on the beacon (no synchronous requests, no await before letting the page continue). Use fetch with keepalive as shown.
  • Don't call DDTracking.init() twice — the second call is ignored with a console warning; all configuration must go through the single call.
  • Don't strip or rewrite the page's URL query parameters — the dm=dc_* marker is how Device Check redirects are attributed; removing it downgrades those journeys to plain slider_loaded / block_page_loaded.
  • Don't send personal data in beacon parameters. The request ID and client ID are DataDome technical identifiers; keep it that way.

Debugging checklist

An expected event did not show up in your analytics platform:

  1. Is the event in the catalog? If not, it is not detected — see "Adding a custom event".
  2. Is it in the EVENT_TYPES map of the domain you tested on? Unmapped events are dropped by design.
  3. Which domain served the page? Configurations are per domain — a domain not carrying the tracking fields (or carrying an older revision) emits nothing or a subset. The Advanced code column of the customizations list (Management → Response Pages) shows which domains carry JavaScript; compare with a domain where the event works.
  4. Check the browser console on a real blocked request (not the preview): the tracker logs initialization problems, and debug: true in DDTracking.init() logs every detected event locally before delivery.
  5. Check the network tab for the request to your collection endpoint: present-but-unanswered points at delivery/ingestion; absent points at detection or mapping.
  6. Close-time events (*_closed) depend on pagehide + keepalive and are inherently best-effort — a missing single occurrence is normal; a systematic absence is not.

Related pages


Did this page help you?