メインコンテンツまでスキップ

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 worksHow it works への直接リンク

  1. Your page adds an iframe that loads https://apps.rokt.com/wsdk/integrations/iframe-plus/index.html.
  2. The iframe sends a ready message. Your page replies with an initialization message that contains your API key and, optionally, the customer's identity.
  3. The iframe loads the Web SDK+ for your API key from apps.rokt-api.com and confirms initialization.
  4. Your page sends calls, such as Rokt.selectPlacements, as messages. The placement renders inside the iframe.
  5. 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 handlingIsolation 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.

AreaWhat it means
ExecutionThe 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 contentsRokt can't read anything your page renders, such as card fields, account details, or order contents.
Page integrityRokt's code has no access to your page's DOM, styles, or scripts. It controls only the contents of the iframe.
LayoutThe 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 tabsThe 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.
InterfaceThe only channel between your page and the iframe is the message contract on this page. The iframe accepts only the supported calls.
Customer dataRokt 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 pinningThe iframe accepts commands only from the origin your page declares in the iframe URL.

What Rokt receivesWhat 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, and pageUrl, 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 referrerPolicy to strict-origin, so the referrer is only your origin. Without that setting, your page's own Referrer-Policy decides what the referrer carries: browsers default to your origin, but a policy such as unsafe-url or no-referrer-when-downgrade sends the full page URL, including its query string. The iframe URL also carries your origin in embedderOrigin.
  • The page URL, when you don't send one. If you omit pageUrl from Rokt.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 launcherOptions control which of them it uses. See Cookie Consent Flags.

Before you startBefore you start への直接リンク

You need:

  • Your Rokt API key. This is the same API_KEY used 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 pageStep 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 codeStep 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 referrerPolicy setting on the iframe.

Neither option loads a script from Rokt into your page.

Reference integration code
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 placementStep 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.

Initialize and select placements
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:

Clean up
await rokt.call('Rokt.close').catch(() => {});
rokt.destroy();
Pay+

If you use Pay+, close the placement when the customer navigates away, including in single-page apps.

Message contractMessage contract への直接リンク

The reference code implements this contract. If you write your own code, follow these rules:

  • Set the iframe's referrerpolicy attribute to strict-origin before 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.origin is https://apps.rokt.com and event.source is your iframe's contentWindow.
  • Use a unique requestId for each init and call message, and match replies by requestId.
  • Every message from the iframe includes protocolVersion: 1.

From your page to the iframeFrom your page to the iframe への直接リンク

typeFieldsWhen to send
rokt-sdkplus-iframe-initrequestId, apiKey, isDevelopmentMode, identifyRequest, launcherOptions, placementPlaceholderIdOnce, after the iframe sends rokt-sdkplus-iframe-ready.
rokt-sdkplus-iframe-callrequestId, path, argsAfter rokt-sdkplus-iframe-init-ok. args is an array.

Initialization fields:

FieldTypeDescription
apiKeystringRequired. Your Rokt API key: 1 to 64 letters, digits, underscores, or hyphens.
isDevelopmentModebooleantrue sends data to the Development environment. Defaults to false.
identifyRequestobjectIdentifies the customer when the Web SDK+ starts. Uses the same format as the Web SDK+ initialization script.
launcherOptionsobjectPrivacy 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.
placementPlaceholderIdstringThe embedded placement's container ID, rokt-{container-name}. The iframe creates this element inside itself.

From the iframe to your pageFrom the iframe to your page への直接リンク

typeFieldsMeaning
rokt-sdkplus-iframe-readyNoneThe iframe has loaded and is waiting for init.
rokt-sdkplus-iframe-init-okrequestId, ignoredLauncherOptionKeysThe Web SDK+ is ready.
rokt-sdkplus-iframe-resultrequestId, resultA call succeeded.
rokt-sdkplus-iframe-errorrequestId, code, messageAn init or call failed. See Errors.
rokt-sdkplus-iframe-resizeheightThe iframe content height in pixels. Set the iframe's height to this value.
rokt-sdkplus-iframe-eventeventName, eventBodyA placement event. See Placement events.
rokt-sdkplus-iframe-session-idsessionIdThe Rokt session ID for the current placement.

Supported callsSupported calls への直接リンク

The iframe accepts only these path values. Results never contain functions or SDK objects.

pathargsresult
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 the PLACEMENT_READY, NO_PLACEMENT, or UNSUPPORTED_PLACEMENT event.
  • 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 in NO_PLACEMENT or UNSUPPORTED_PLACEMENT. To select placements again, call Rokt.close first. Otherwise the call fails with SELECTION_ACTIVE.
  • pageUrl tells 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 omit pageUrl, the iframe uses its referrer. With the reference code, that is only your origin. See What Rokt receives.
  • placementPlaceholderId overrides the container ID from init for this placement.

Placement eventsPlacement 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.

ErrorsErrors への直接リンク

codeMeaningWhat to do
MISSING_API_KEY, INVALID_API_KEYapiKey is missing or malformed.Check the API key.
APP_JS_LOAD_FAILEDThe 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_FAILEDThe Web SDK+ didn't load or become ready in time.Create a new iframe.
ALREADY_INITIALIZEDThe iframe received a second init.Send init once per iframe.
NOT_INITIALIZEDA call arrived before init-ok.Wait for init-ok.
FORBIDDEN_PATHThe path isn't a supported call.Use a supported call.
SELECTION_ACTIVEA selection is still active. It stays active until Rokt.close, even after its placement closes.Call Rokt.close first.
NO_SELECTIONRokt.close found no placement to close.No action needed.
CALL_FAILEDThe call failed or didn't finish in time.See Time limits and recovery.
MISSING_MPARTICLEThe Web SDK+ isn't available in the iframe.Create a new iframe.
INVALID_ORIGIN, INVALID_SOURCEThe 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 recoveryTime 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.

LimitationsLimitations への直接リンク

  • 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_PLACEMENT event.
  • 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 identifyRequest on 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 iframeMoving 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 iframeWeb SDK+ iframe
Iframe URL/wsdk/integrations/iframe/index.html/wsdk/integrations/iframe-plus/index.html?embedderOrigin=…
CredentialRokt account IDRokt API key
Ready messagerokt-wsdk-iframe-readyrokt-sdkplus-iframe-ready
Start a placementOne rokt-wsdk-partner-select-placements message with the account ID, page identifier, and attributesAn init message with the API key and identifyRequest, then a Rokt.selectPlacements call with the page identifier and attributes
Heightrokt-wsdk-iframe-resizerokt-sdkplus-iframe-resize
Eventsrokt-wsdk-iframe-report-eventrokt-sdkplus-iframe-event
Session IDrokt-wsdk-iframe-report-session-idrokt-sdkplus-iframe-session-id
Results and errorsNot reportedOne result or error per request

Pass the customer's email in identifyRequest, and keep your other attributes in the Rokt.selectPlacements call.

Test your integrationTest your integration への直接リンク

  1. Set isDevelopmentMode to true and use your test page identifier.
  2. Confirm that createRoktIframe resolves and ignoredLauncherOptionKeys is empty.
  3. Confirm that the placement renders, the iframe grows to fit it, and you receive PLACEMENT_READY.
  4. Close the placement and destroy the iframe when the customer leaves the page.
  5. Before going live, set isDevelopmentMode to false and use your production page identifier.
SymptomCheck
No rokt-sdkplus-iframe-ready messageYour Content Security Policy allows https://apps.rokt.com in frame-src, and the iframe URL is correct.
Ready, but init times outembedderOrigin 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_FAILEDThe API key matches your Web SDK+ initialization script.
NO_PLACEMENT eventThe page identifier and container ID match the values from your Rokt account manager.
UNSUPPORTED_PLACEMENT eventThe 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 pixelsYour code applies rokt-sdkplus-iframe-resize messages to the iframe's height.
SELECTION_ACTIVECall Rokt.close before selecting placements again, even if the earlier placement has already closed.
PLACEMENT_READY arrives, but nothing showsCheck for an UNSUPPORTED_PLACEMENT or NO_PLACEMENT event for the same request. Either can arrive before or after PLACEMENT_READY.
この記事は役に立ちましたか?