Isolated iframe for the Web SDK+
The Web SDK+ can run inside a Rokt-hosted iframe instead of directly in your page. This puts the browser's same-origin boundary between Rokt and your page: Rokt's code runs on a separate origin and can't read or modify your page's DOM, scripts, or storage. No Rokt script runs in your page. The iframe isn't sandboxed, so read Isolation and data handling for what the boundary covers and what it doesn't.
Use this integration only on pages where Rokt code can't run in the page itself, for example a payment page where every third-party script must be inventoried and approved. Everywhere else, use the standard Web SDK+ integration. It renders placements sooner and supports every placement type.
If you already embed the Rokt-hosted iframe with an account ID, see Moving from the Web SDK iframe.
How it worksLien direct vers How it works
- Your page adds an iframe that loads
https://apps.rokt.com/wsdk/integrations/iframe-plus/index.html. - The iframe sends a ready message. Your page replies with an initialization message that contains your API key and, optionally, the customer's identity.
- The iframe loads the Web SDK+ for your API key from
apps.rokt-api.comand confirms initialization. - Your page sends calls, such as
Rokt.selectPlacements, as messages. The placement renders inside the iframe. - The iframe sends results, placement events, the Rokt session ID, and its content height back to your page.
All communication between your page and the iframe uses window.postMessage. Your page decides exactly what data it puts in those messages.
Isolation and data handlingLien direct vers Isolation and data handling
The boundary is the browser's same-origin policy. It stops Rokt's code from reaching into your page. It doesn't sandbox the iframe, and it doesn't limit what the Web SDK+ collects inside the iframe.
| Area | What it means |
|---|---|
| Execution | The Web SDK+ runs on Rokt's origin. The browser's same-origin policy prevents script access between the iframe and your page in either direction. |
| Page contents | Rokt can't read anything your page renders, such as card fields, account details, or order contents. |
| Page integrity | Rokt's code has no access to your page's DOM, styles, or scripts. It controls only the contents of the iframe. |
| Layout | The iframe reports its content height, and the reference code sets the iframe to that height. This is the one change your page makes at the iframe's request. |
| Navigation and new tabs | The reference code doesn't set a sandbox attribute, because placements and Pay+ haven't been validated inside a sandboxed iframe. Like any embedded page that isn't sandboxed, the iframe can open a new tab or navigate the top-level page. Browsers generally require the customer to have interacted with the iframe before it can open a tab or send the top-level page to another site. |
| Interface | The only channel between your page and the iframe is the message contract on this page. The iframe accepts only the supported calls. |
| Customer data | Rokt can't read customer data from your page. The customer identifiers and attributes it receives are the ones your page sends. Other data reaches Rokt without your page sending it. See What Rokt receives. |
| Origin pinning | The iframe accepts commands only from the origin your page declares in the iframe URL. |
What Rokt receivesLien direct vers What Rokt receives
Moving the Web SDK+ into an iframe stops it from reading your page. It doesn't turn off the data the Web SDK+ and the browser handle themselves.
- What your page sends. Your API key,
identifyRequest, attributes, andpageUrl, in the messages on this page. - What the browser sends. Loading the iframe is a normal browser request to Rokt. It carries the customer's IP address, the browser's user agent, and a referrer. The reference code sets the iframe's
referrerPolicytostrict-origin, so the referrer is only your origin. Without that setting, your page's ownReferrer-Policydecides what the referrer carries: browsers default to your origin, but a policy such asunsafe-urlorno-referrer-when-downgradesends the full page URL, including its query string. The iframe URL also carries your origin inembedderOrigin. - The page URL, when you don't send one. If you omit
pageUrlfromRokt.selectPlacements, the iframe uses its referrer instead, so the page URL is whatever the referrer carries. - What the Web SDK+ creates. Inside the iframe, the Web SDK+ creates its own identifiers, such as a Rokt session ID and browser identifiers, and keeps them in browser storage under Rokt's domain. The privacy options in
launcherOptionscontrol which of them it uses. See Cookie Consent Flags.
Before you startLien direct vers Before you start
You need:
- Your Rokt API key. This is the same
API_KEYused in the Web SDK+ initialization script. - The page identifier for the page, for example
prod.rokt.payments, and the container ID for the embedded placement,rokt-{container-name}. Your Rokt account manager provides both.
Step 1: Prepare the pageLien direct vers Step 1: Prepare the page
Add an empty container where the placement should appear. The integration code creates the iframe inside it.
<div id="rokt-iframe-container"></div>
The integration code adds embedderOrigin to the iframe URL, set to your page's origin. The iframe accepts the first initialization message only from that origin, and then accepts commands only from it.
https://apps.rokt.com/wsdk/integrations/iframe-plus/index.html?embedderOrigin=https%3A%2F%2Fwww.example.com
If your Content Security Policy restricts frames, add https://apps.rokt.com to frame-src. Your page doesn't need script-src or connect-src entries for Rokt, because no Rokt script runs in your page.
Step 2: Add the integration codeLien direct vers Step 2: Add the integration code
Choose one of these options. Both use the same Rokt-hosted iframe and work the same way.
- Option A: Copy the reference code. Copy the code below into your own codebase. It runs from your domain, and you own, review, and version-control every line.
- Option B: Write your own code. Implement the message contract directly. Keep the origin, source, and request ID checks that the reference code performs, and its
referrerPolicysetting on the iframe.
Neither option loads a script from Rokt into your page.
function createRoktIframe(options) {
const HOST_URL = 'https://apps.rokt.com/wsdk/integrations/iframe-plus/index.html';
const PREFIX = 'rokt-sdkplus-iframe-';
const READY_TIMEOUT_MS = 15000;
const INIT_TIMEOUT_MS = 30000;
const CALL_TIMEOUT_MS = 35000;
const url = new URL(HOST_URL);
url.searchParams.set('embedderOrigin', window.location.origin);
const hostOrigin = url.origin;
const iframe = document.createElement('iframe');
// Send Rokt only this page's origin as the referrer, whatever this page's own Referrer-Policy is.
iframe.referrerPolicy = 'strict-origin';
iframe.src = url.href;
iframe.title = options.title || 'Rokt offers';
iframe.allow = 'payment';
iframe.style.cssText = 'display: block; width: 100%; height: 0; border: 0;';
const pending = new Map();
let requestCount = 0;
let destroyed = false;
let onReady;
let readyTimer;
function settle(requestId, complete) {
const entry = pending.get(requestId);
if (!entry) return;
pending.delete(requestId);
clearTimeout(entry.timer);
complete(entry);
}
function send(message, timeoutMs) {
return new Promise((resolve, reject) => {
if (destroyed) {
reject(new Error('The Rokt iframe was destroyed'));
return;
}
requestCount += 1;
const requestId = `rokt-${requestCount}-${Date.now()}`;
const timer = setTimeout(() => {
settle(requestId, (entry) => entry.reject(new Error(`No reply to ${message.type} within ${timeoutMs} ms`)));
}, timeoutMs);
pending.set(requestId, { resolve, reject, timer });
try {
iframe.contentWindow.postMessage({ ...message, requestId }, hostOrigin);
} catch (error) {
settle(requestId, (entry) => entry.reject(error));
}
});
}
function handleMessage(event) {
if (event.origin !== hostOrigin || event.source !== iframe.contentWindow) return;
const data = event.data;
if (!data || data.protocolVersion !== 1 || typeof data.type !== 'string' || !data.type.startsWith(PREFIX)) return;
switch (data.type.slice(PREFIX.length)) {
case 'ready':
if (onReady) {
const ready = onReady;
onReady = undefined;
ready();
}
break;
case 'init-ok':
case 'result':
settle(data.requestId, (entry) => entry.resolve(data));
break;
case 'error':
settle(data.requestId, (entry) => {
const error = new Error(data.message);
error.code = data.code;
entry.reject(error);
});
break;
case 'resize':
if (Number.isFinite(data.height) && data.height >= 0) iframe.style.height = `${data.height}px`;
break;
case 'event':
if (options.onEvent) options.onEvent(data.eventName, data.eventBody);
break;
case 'session-id':
if (options.onSessionId) options.onSessionId(data.sessionId);
break;
}
}
function destroy() {
destroyed = true;
onReady = undefined;
clearTimeout(readyTimer);
window.removeEventListener('message', handleMessage);
for (const requestId of [...pending.keys()]) {
settle(requestId, (entry) => entry.reject(new Error('The Rokt iframe was destroyed')));
}
iframe.remove();
}
function call(path, ...args) {
return send({ type: `${PREFIX}call`, path, args }, CALL_TIMEOUT_MS).then((reply) => reply.result);
}
window.addEventListener('message', handleMessage);
options.container.appendChild(iframe);
return new Promise((resolve, reject) => {
readyTimer = setTimeout(() => {
destroy();
reject(new Error('The Rokt iframe did not become ready'));
}, READY_TIMEOUT_MS);
onReady = () => {
clearTimeout(readyTimer);
send(
{
type: `${PREFIX}init`,
apiKey: options.apiKey,
isDevelopmentMode: options.isDevelopmentMode === true,
identifyRequest: options.identifyRequest,
launcherOptions: options.launcherOptions,
placementPlaceholderId: options.placementPlaceholderId,
},
INIT_TIMEOUT_MS,
).then(
(reply) => resolve({ call, destroy, ignoredLauncherOptionKeys: reply.ignoredLauncherOptionKeys || [] }),
(error) => {
destroy();
reject(error);
},
);
};
});
}
Step 3: Initialize and show a placementLien direct vers Step 3: Initialize and show a placement
Call createRoktIframe with your configuration. It resolves when the Web SDK+ is ready inside the iframe. Then call Rokt.selectPlacements with the page identifier and your attributes.
const rokt = await createRoktIframe({
container: document.getElementById('rokt-iframe-container'),
apiKey: 'YOUR_API_KEY',
// Set to false when your integration is ready for production data.
isDevelopmentMode: true,
identifyRequest: {
userIdentities: {
email: 'j.smith@example.com',
},
},
launcherOptions: {
noFunctional: false,
noTargeting: false,
},
placementPlaceholderId: 'rokt-{container-name}',
onEvent: (eventName, eventBody) => {
console.log('Rokt event', eventName, eventBody);
},
onSessionId: (sessionId) => {
console.log('Rokt session ID', sessionId);
},
});
await rokt.call('Rokt.selectPlacements', {
identifier: 'prod.rokt.payments',
pageUrl: window.location.origin + window.location.pathname,
attributes: {
email: 'j.smith@example.com',
lastname: 'Smith',
country: 'US',
currency: 'USD',
amount: 129.95,
paymenttype: 'credit_card',
},
});
Use the same identifyRequest and attribute names as the Web SDK+ integration. If you use Pay+, include the payment attributes it requires.
When the customer leaves the page, close the placement and remove the iframe:
await rokt.call('Rokt.close').catch(() => {});
rokt.destroy();
If you use Pay+, close the placement when the customer navigates away, including in single-page apps.
Message contractLien direct vers Message contract
The reference code implements this contract. If you write your own code, follow these rules:
- Set the iframe's
referrerpolicyattribute tostrict-originbefore the iframe loads, so the request to Rokt carries only your origin as its referrer. - Send every message to the iframe with the target origin
https://apps.rokt.com. Never use*. - Accept a message only if
event.originishttps://apps.rokt.comandevent.sourceis your iframe'scontentWindow. - Use a unique
requestIdfor eachinitandcallmessage, and match replies byrequestId. - Every message from the iframe includes
protocolVersion: 1.
From your page to the iframeLien direct vers From your page to the iframe
type | Fields | When to send |
|---|---|---|
rokt-sdkplus-iframe-init | requestId, apiKey, isDevelopmentMode, identifyRequest, launcherOptions, placementPlaceholderId | Once, after the iframe sends rokt-sdkplus-iframe-ready. |
rokt-sdkplus-iframe-call | requestId, path, args | After rokt-sdkplus-iframe-init-ok. args is an array. |
Initialization fields:
| Field | Type | Description |
|---|---|---|
apiKey | string | Required. Your Rokt API key: 1 to 64 letters, digits, underscores, or hyphens. |
isDevelopmentMode | boolean | true sends data to the Development environment. Defaults to false. |
identifyRequest | object | Identifies the customer when the Web SDK+ starts. Uses the same format as the Web SDK+ initialization script. |
launcherOptions | object | Privacy and test options. Only the boolean options doNotShareOrSell, noDeviceId, noFunctional, noTargeting, and sandbox are applied. The iframe ignores other keys and lists them in ignoredLauncherOptionKeys. |
placementPlaceholderId | string | The embedded placement's container ID, rokt-{container-name}. The iframe creates this element inside itself. |
From the iframe to your pageLien direct vers From the iframe to your page
type | Fields | Meaning |
|---|---|---|
rokt-sdkplus-iframe-ready | None | The iframe has loaded and is waiting for init. |
rokt-sdkplus-iframe-init-ok | requestId, ignoredLauncherOptionKeys | The Web SDK+ is ready. |
rokt-sdkplus-iframe-result | requestId, result | A call succeeded. |
rokt-sdkplus-iframe-error | requestId, code, message | An init or call failed. See Errors. |
rokt-sdkplus-iframe-resize | height | The iframe content height in pixels. Set the iframe's height to this value. |
rokt-sdkplus-iframe-event | eventName, eventBody | A placement event. See Placement events. |
rokt-sdkplus-iframe-session-id | sessionId | The Rokt session ID for the current placement. |
Supported callsLien direct vers Supported calls
The iframe accepts only these path values. Results never contain functions or SDK objects.
path | args | result |
|---|---|---|
Identity.identify, Identity.login, Identity.logout | [identifyRequest] | { httpCode, mpid } |
Identity.setUserAttribute | [key, value] | { ok: true } |
Identity.removeUserAttribute | [key] | { ok: true } |
logPageView | [eventName, attributes] | None |
logEvent | [eventName, eventType, attributes]. eventType is a number, for example 8 for Other. | None |
eCommerce.logProductAction | [{ action, products, attributes, customFlags, transactionAttributes }]. action is a product action name such as "Purchase". Each product is { name, sku, price, quantity, variant, category, brand, position }. | None |
eCommerce.logImpression | [{ name, products, attributes }] | None |
Rokt.selectPlacements | [{ identifier, attributes, pageUrl, placementPlaceholderId }] | { ok: true } |
Rokt.close | [] | { ok: true } |
Rokt.terminate | [] | { ok: true } |
Rokt.hashAttributes | [attributes] | The hashed attributes |
Rokt.hashSha256 | [value] | The SHA-256 hash |
Notes on Rokt.selectPlacements:
- It resolves with
{ ok: true }when the Web SDK+ accepts the request, not when a placement renders. Watch for thePLACEMENT_READY,NO_PLACEMENT, orUNSUPPORTED_PLACEMENTevent. - The iframe holds one selection at a time, and a selection stays active until you call
Rokt.close. That includes a selection whose placement has already closed, and one that ended inNO_PLACEMENTorUNSUPPORTED_PLACEMENT. To select placements again, callRokt.closefirst. Otherwise the call fails withSELECTION_ACTIVE. pageUrltells Rokt which page the customer is on. The iframe removes any user name, password, and fragment, but keeps the query string, so pass a URL without sensitive query parameters. If you omitpageUrl, the iframe uses its referrer. With the reference code, that is only your origin. See What Rokt receives.placementPlaceholderIdoverrides the container ID frominitfor this placement.
Placement eventsLien direct vers Placement events
eventName is the name of a Web SDK+ placement event, such as PLACEMENT_READY, PLACEMENT_INTERACTIVE, or OFFER_ENGAGEMENT, and eventBody is the event's data. The iframe also sends NO_PLACEMENT when Rokt has no placement to show for the request.
If Rokt returns a placement that isn't embedded, such as an overlay, the iframe closes it and sends UNSUPPORTED_PLACEMENT with an eventBody of { reason: 'NOT_EMBEDDED' }. When that leaves nothing to show, NO_PLACEMENT follows, so code that already handles NO_PLACEMENT needs no change.
The iframe still forwards the Web SDK+ events for a placement it closes this way, so PLACEMENT_READY and PLACEMENT_CLOSED can arrive as well, before or after UNSUPPORTED_PLACEMENT and NO_PLACEMENT. Don't treat PLACEMENT_READY on its own as proof that a placement is on screen. If your page shows anything around the iframe when a placement appears, such as a heading or spacing, base it on the height from rokt-sdkplus-iframe-resize instead. A placement the iframe can't show adds no height, and the height returns to 0 when nothing is left showing in the iframe.
ErrorsLien direct vers Errors
code | Meaning | What to do |
|---|---|---|
MISSING_API_KEY, INVALID_API_KEY | apiKey is missing or malformed. | Check the API key. |
APP_JS_LOAD_FAILED | The Web SDK+ file for your API key didn't load. | Check the API key and the customer's network, then create a new iframe. |
INIT_FAILED | The Web SDK+ didn't load or become ready in time. | Create a new iframe. |
ALREADY_INITIALIZED | The iframe received a second init. | Send init once per iframe. |
NOT_INITIALIZED | A call arrived before init-ok. | Wait for init-ok. |
FORBIDDEN_PATH | The path isn't a supported call. | Use a supported call. |
SELECTION_ACTIVE | A selection is still active. It stays active until Rokt.close, even after its placement closes. | Call Rokt.close first. |
NO_SELECTION | Rokt.close found no placement to close. | No action needed. |
CALL_FAILED | The call failed or didn't finish in time. | See Time limits and recovery. |
MISSING_MPARTICLE | The Web SDK+ isn't available in the iframe. | Create a new iframe. |
INVALID_ORIGIN, INVALID_SOURCE | The message didn't come from the pinned origin or from the parent window. | Send messages only from the page that embeds the iframe. |
If init comes from an origin that doesn't match embedderOrigin, the iframe doesn't reply at all, and your init times out.
Time limits and recoveryLien direct vers Time limits and recovery
The iframe waits up to 13 seconds for the Web SDK+ file and up to 13 more seconds for it to become ready. Identity and Rokt.selectPlacements calls fail with CALL_FAILED after 30 seconds. The reference code allows 15 seconds for the ready message, 30 seconds for init, and 35 seconds for each call, so the iframe's own error arrives first. Browsers can delay timers in background tabs.
A timeout doesn't prove that a call had no effect, so don't retry identity, commerce, or placement calls automatically. If initialization fails, remove the iframe and create a new one.
LimitationsLien direct vers Limitations
- Embedded placements only. Overlay and interstitial placements can't render outside the iframe, so they aren't supported. If Rokt returns one, the iframe closes it and sends the
UNSUPPORTED_PLACEMENTevent. - No extensions. Features that need
mParticle.Rokt.use()aren't available. - No first-party domains. The iframe always loads the Web SDK+ from
apps.rokt-api.com. - No cross-site identity storage. Browsers partition and may clear storage in third-party iframes, so pass
identifyRequeston every page. - Slower first render. The iframe adds a page load before the Web SDK+ starts, so placements render later than with the standard integration.
Moving from the Web SDK iframeLien direct vers Moving from the Web SDK iframe
The Web SDK+ iframe uses a different URL, credential, and message contract from the Web SDK iframe. Update your integration code as follows.
| Web SDK iframe | Web SDK+ iframe | |
|---|---|---|
| Iframe URL | /wsdk/integrations/iframe/index.html | /wsdk/integrations/iframe-plus/index.html?embedderOrigin=… |
| Credential | Rokt account ID | Rokt API key |
| Ready message | rokt-wsdk-iframe-ready | rokt-sdkplus-iframe-ready |
| Start a placement | One rokt-wsdk-partner-select-placements message with the account ID, page identifier, and attributes | An init message with the API key and identifyRequest, then a Rokt.selectPlacements call with the page identifier and attributes |
| Height | rokt-wsdk-iframe-resize | rokt-sdkplus-iframe-resize |
| Events | rokt-wsdk-iframe-report-event | rokt-sdkplus-iframe-event |
| Session ID | rokt-wsdk-iframe-report-session-id | rokt-sdkplus-iframe-session-id |
| Results and errors | Not reported | One result or error per request |
Pass the customer's email in identifyRequest, and keep your other attributes in the Rokt.selectPlacements call.
Test your integrationLien direct vers Test your integration
- Set
isDevelopmentModetotrueand use your test page identifier. - Confirm that
createRoktIframeresolves andignoredLauncherOptionKeysis empty. - Confirm that the placement renders, the iframe grows to fit it, and you receive
PLACEMENT_READY. - Close the placement and destroy the iframe when the customer leaves the page.
- Before going live, set
isDevelopmentModetofalseand use your production page identifier.
| Symptom | Check |
|---|---|
No rokt-sdkplus-iframe-ready message | Your Content Security Policy allows https://apps.rokt.com in frame-src, and the iframe URL is correct. |
Ready, but init times out | embedderOrigin exactly matches your page's origin, including the protocol, subdomain, and port. A sandboxed page has no origin and can't use this integration. |
INVALID_API_KEY or APP_JS_LOAD_FAILED | The API key matches your Web SDK+ initialization script. |
NO_PLACEMENT event | The page identifier and container ID match the values from your Rokt account manager. |
UNSUPPORTED_PLACEMENT event | The page in your Rokt account uses an embedded layout. Ask your Rokt account manager to replace an overlay layout with an embedded one. |
| The placement renders but the iframe stays at 0 pixels | Your code applies rokt-sdkplus-iframe-resize messages to the iframe's height. |
SELECTION_ACTIVE | Call Rokt.close before selecting placements again, even if the earlier placement has already closed. |
PLACEMENT_READY arrives, but nothing shows | Check for an UNSUPPORTED_PLACEMENT or NO_PLACEMENT event for the same request. Either can arrive before or after PLACEMENT_READY. |