Response Page Custom JavaScript
Overview
Custom JavaScript lets you extend DataDome's response pages - the Slider page, the Block page, and the Device Check page (only in visible mode) - with your own behavior: analytics and tracking events, DOM adjustments, dynamic text, or visual effects combined with custom CSS.
EligibilityCustom JavaScript is part of Advanced Response Page Customization, available exclusively to customers on an Enterprise or Premium plan.
Your code runs on a security-critical pageA JavaScript error here can prevent real users from passing the challenge. Follow the defensive coding rules below, they are the difference between a safe customization and an incident. Saving publishes your code with no draft state; it reaches live pages after a cache reload that can take several minutes.
Where your code runs: the iframe model
When DataDome blocks a request on your site, your page receives a small response that loads the challenge inside a DataDome iframe. Your custom JavaScript runs inside that iframe's document, which is served from a DataDome domain, not from your site. Consequences:
- You cannot access your own site's cookies, storage, or DOM from the response page. If you need data from your site, it isn't available here.
- Network calls (
fetch) go out from a DataDome origin, your tracking endpoint must accept cross-origin requests. - The iframe is sandboxed: redirecting the user or opening new tabs or popups from the response page is blocked and silently fails.
- The iframe communicates with your page via
postMessageinternally; do not interfere with messages you did not create.
The three JavaScript sections
The JavaScript fields are edited in your dashboard: go to Management → Response Pages, open the customization of the domain to configure (Default applies to all domains that have no customization of their own), then open the Advanced code tab and select the Header JS, Top body JS, or Bottom body JS editor. The same code runs on the Slider, Block, and Device Check pages, whatever page is selected in the Page selector: use that selector and Refresh preview to check your changes on each page before saving. Code is auto-formatted on paste and on save (you can also click Format), and the size used is displayed against the limit of each field.
Paste plain JavaScript, without a<script>tagThe JavaScript editors expect JavaScript code only: DataDome wraps the content of each field in a
<script>element when injecting it into the page. Do not add<script>tags yourself, and start from a self-contained IIFE:(function (w) { // your code })(window);
There are three separate fields. They are all injected into the same challenge document, but at different positions, which determines what exists when your code runs:
| Section | Injected at | What exists when it runs | Typical use |
|---|---|---|---|
| Header JS | Inside <head>, before the page body is parsed | No DOM yet. No DataDome globals yet. | Early setup: define helper libraries, start loading a third-party script, install hooks that must exist before anything renders |
| Top Body JS | Immediately after <body> opens | document.body exists but the page content does not yet | Rarely needed in practice — prefer Bottom Body JS |
| Bottom Body JS | End of <body>, after the page markup | The full page DOM is present. The CAPTCHA library and its configuration have not loaded yet — they execute right after this section | The main section. DOM changes, event listeners, MutationObservers, analytics |
Additional facts that apply to all three sections:
- They run on all page types — Slider, Block, and Device Check (Device Check only when its display is enabled for your account; there is no separate Device Check configuration — the same shared fields apply). The Block page never loads a Slider library, so guard any Slider-specific logic by page type.
- Even in Bottom Body JS, DataDome's globals and the Slider library are not available yet at execution time. Read them lazily — inside event handlers or observers that fire later, when they exist.
- Each field has its own size cap — 15 KB for Header JS, 5 KB for Top Body JS, 40 KB for Bottom Body JS — and is injected verbatim with no content validation, which is why the coding rules below matter.
Detecting the page type
Every response page carries a response-type marker on its <body> element: a class (dd-response-page--captcha, dd-response-page--hard-block, dd-response-page--device-check) and a matching data-dd-response-page attribute. Read the attribute to branch your logic per page type:
function getPageType(w) {
var marker = w.document.body && w.document.body.getAttribute('data-dd-response-page');
if (marker) {
return marker; // 'captcha' | 'hard-block' | 'device-check'
}
// Fallback for pages rendered before the marker was introduced
if (w.ddoptions && w.ddoptions.responsePage) {
return w.ddoptions.responsePage === 'block' ? 'hard-block' : 'captcha';
}
if (w.interstitialChallenge) {
return 'device-check';
}
var captchaContainer = w.document.getElementById('captcha-container');
var challengeContainer = w.document.getElementById('ddv1-captcha-container');
var deviceCheck = w.document.getElementsByClassName('device-check__main');
if (captchaContainer) {
return challengeContainer ? 'captcha' : 'hard-block';
}
if (deviceCheck.length > 0) {
return 'device-check';
}
return 'unknown';
}To scope CSS per page type, no JavaScript is needed: target the body class directly (body.dd-response-page--captcha .my-element { ... }) — see the custom CSS page for details.
Dynamic tokens
Three tokens are replaced server-side in all three JavaScript sections (they do not work in custom CSS):
| Token | Replaced with |
|---|---|
{%USER_IP_ADDRESS%} | The end user's IP address |
{%CUSTOMER_NAME%} | Your account name |
{%CUSTOMER_WEBSITE%} | Your website URL |
Coding requirements
Your code must survive on a page whose markup DataDome can evolve at any time, in old browsers, with no dependencies. All customizations must follow these rules:
-
Wrap everything in an IIFE — never leak to the global scope:
(function (w) { // your code })(window); - Vanilla JavaScript only. No jQuery, lodash, axios, or other libraries.
-
Null-check every DOM lookup before using it. Collections must be length-checked before indexing:
var el = w.document.querySelector('[data-dd-captcha-contact-form]'); if (el) { el.classList.add('my-class'); } - No optional chaining (
?.) or other very recent syntax — the page must work on older browsers. - Prefer
data-dd-*attribute selectors over IDs, class names, or text content. IDs and classes are less stable; visible text is translated and customizable. - Wrap network calls in
try/catchand fail silently. Tracking must never break the challenge. -
Run DOM logic when the DOM is ready:
function ready(w, callback) { if (w.document.readyState !== 'loading') { callback(); return; } w.document.addEventListener('DOMContentLoaded', callback); }
Stable selectors
| Element | Selector |
|---|---|
| Response-type marker | body[data-dd-response-page] / body.dd-response-page--* |
| Page container | #captcha-container |
| Slider widget container | #ddv1-captcha-container |
| Feedback button | [data-dd-captchacontact-support-submit] |
| Feedback form wrapper | [data-dd-captcha-contact-support] |
| Feedback form | [data-dd-captcha-contact-form] |
| Feedback comment field | [data-dd-captcha-contact-input] |
| Feedback submit button | [data-dd-captcha-contact-submit] |
Observable events
The response page exposes DOM-level signals you can observe to track the user journey — typically to send events to your analytics endpoint.
| Event | How to detect it |
|---|---|
| Slider displayed | sliderLoaded CustomEvent dispatched on window when the widget initializes (event.detail carries the widget options) |
| Slider completed | The hidden element #analyticsCaptchaPassed gets its data-analytics-captcha-passed attribute set — watch it with a MutationObserver |
| Slider failed | The .sliderContainer element gains the slider-error class — watch class mutations |
| Audio challenge completed or failed | .audio-captcha-verify-button (or .audio-captcha-input-container) gets data-result="success" or data-result="error" |
| User leaves the page | Standard pagehide event |
Additional observable state changes (all via MutationObserver): captcha-success / captcha-error classes on #captcha__element, slider-success on .sliderContainer, sliderContainer_active while the user drags the slider, and active on #captcha__offline when the browser goes offline.
Slider passed eventsFor security reasons, DataDome does not disclose on the Slider page whether a challenge solver was detected or whether the passing attempt was blocked.
The page only indicates that the slider or audio challenge was completed. It does not confirm that the challenge was successfully passed.
To determine the final outcome, inspect the enriched headers returned with the subsequent server-side request. This information can then be used alongside client-side events in your analytics platform.
Example: sending challenge events to your analytics endpoint
Complete Bottom Body JS example — display, pass, and fail events POSTed to your endpoint:
(function (w) {
function send(eventName) {
try {
w.fetch('https://analytics.example.com/events', {
method: 'POST',
keepalive: true,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
event: eventName,
// window.ddm is populated by the page after this script runs —
// read it lazily, inside the handlers below, never at top level.
referer: w.ddm && w.ddm.referer,
userAgent: w.ddm && w.ddm.ua
})
});
} catch (e) { /* tracking must never break the page */ }
}
// 1. Slider displayed
w.addEventListener('sliderLoaded', function () {
send('captcha_displayed');
});
// 2. Slider passed
var passedEl = w.document.getElementById('analyticsCaptchaPassed');
if (passedEl) {
new MutationObserver(function (mutations) {
for (var i = 0; i < mutations.length; i++) {
if (mutations[i].attributeName === 'data-analytics-captcha-passed') {
send('captcha_passed');
}
}
}).observe(passedEl, { attributes: true });
}
// 3. Slider failed
var sliders = w.document.getElementsByClassName('sliderContainer');
if (sliders.length > 0) {
new MutationObserver(function (mutations) {
for (var i = 0; i < mutations.length; i++) {
if (mutations[i].target.classList.contains('slider-error')) {
send('captcha_failed');
}
}
}).observe(sliders[0], { attributes: true, attributeFilter: ['class'] });
}
})(window);Example: adding a branded element to the page
Use Bottom Body JS to add structure — e.g. a branded header above the challenge. Give injected elements a class name of your own and style them through the CSS editor of the Advanced code tab:
(function (w) {
var container = w.document.getElementById('captcha-container');
if (!container) { return; }
var header = w.document.createElement('div');
header.className = 'my-brand-header';
var logo = w.document.createElement('img');
logo.src = 'https://cdn.example.com/logo.svg';
logo.alt = '{%CUSTOMER_NAME%}';
header.appendChild(logo);
container.prepend(header);
})(window);What to avoid
- Redirecting users or opening new tabs. Blocked by the sandbox of the iframe the page runs in — such navigation silently fails.
- Modifying the Slider widget internals (the puzzle and slider) or interfering with its scripts. This is a security surface.
- Selecting elements by visible text, translated labels, or deep DOM paths (
parentNodechains, sibling traversal). These break silently when DataDome updates the page or when translations change. - Large inline assets (e.g. base64 or SVG data-URIs) — they bloat the page and have caused blank-page incidents. Host assets on a CDN and reference them by URL.
- Assuming the Slider library or DataDome globals exist at load time. Even in Bottom Body JS they load after your code — access them inside event handlers only.
- Heavy synchronous work at load time — it delays the challenge and hurts your pass rate.
- Expecting your site's cookies or storage — the page runs on a DataDome origin (see the iframe model above).
If your use case calls for one of the above, please contact your customer representative to discuss it.
Testing and rollout
Test on a test domain first
Your JavaScript is stored per domain — use that to validate changes on a test domain before any production traffic runs them:
- Pick a test domain — a staging or low-traffic domain that is already protected by DataDome. The response page is served by DataDome, so traffic on that domain must go through your DataDome integration.
- Create a customization for that domain only. In Management → Response Pages, click New customization, enter your test domain, and start from A copy of a customization (Default) so the domain keeps its current behavior. Then add your code in the Advanced code tab and save. A domain-specific customization overrides the Default one, so your other domains keep serving their configuration untouched.
- Trigger the response page on the test domain. The preview shows your changes rendered, but JavaScript must be validated on the real page: create a custom rule (Access Control → Custom Rules) scoped to your test domain and a narrow condition you control — for example your office IP — with a Slider (or Block) response. Visiting the domain from a matching client then serves the real response page executing your code.
- Validate with the checklist below, then roll the validated code out with Copy to Other Domains: select Header, Top body & Bottom body JS and the destination domains (Default and/or your production domains). Remove the triggering custom rule when you are done.
Caching & propagationSaving publishes your code with no draft state; a cache reload can take several minutes before the change reaches all live pages. Response page texts and translations are cached more aggressively for performance: a translation update can take up to 15 minutes to show — including in the preview. Wait for the cache to refresh before concluding a change did not work.
Validation checklist
- Test all page types (Slider, Block, and Device Check) and the audio-accessibility flow; your code runs on all of them.
- Watch the browser console on a real blocked request — your code must produce zero uncaught errors.
- Keep the previous version so you can roll back fast.
- After rollout, monitor your Slider pass rate — a JavaScript regression shows up as a pass-rate drop.
Related pages
Updated about 1 hour ago

