Help / Embed
Control variants from your page
For developers — read a product's options from the 3D view and switch variants with your own buttons, through the <df-view> element or an iframe and postMessage.
The 3D view already has its own variant buttons inside it (set up on the Options tab). If your shop has its own selector — buttons, swatches, a dropdown — it can drive the same variants through the Viewer API: your page asks the 3D view which options exist, draws its own controls and switches variants with a command. Nothing of ours is drawn on your page, and the built-in buttons stay in sync with yours.
When you need it
You do not need it for an ordinary embed: the code from the Embed window already shows the product with its built-in buttons and can open on chosen starting variants.
You need it when your page itself must know or change the variant — your own selector, a variant tied to your product form, or several controls that must agree.
- Use it with In the page code or with the
<df-view>element. With Tile + window the tile only shows a poster and does not start the 3D view, so there is nothing for your selector to talk to. - If the product starts On click or When seen, the 3D view reports its options only after it has started — after the click, or once the block is in view. The complete examples draw your buttons at that moment.
Two ways use the same protocol (version 1). Pick one per 3D view:
| Way | Best for |
|---|---|
The <df-view> element | Most pages: one script tag, an element, events and a method that returns true or false. |
An iframe and postMessage | Pages that cannot load our script, or that already manage their own frames. |
What the 3D view reports
The options come from the published product:
{
"groups": [
{
"slug": "metal",
"label": "Metal",
"defaultVariant": "yellow-gold",
"variants": [
{ "slug": "yellow-gold", "label": "Yellow gold", "swatch": "#e8b455" },
{ "slug": "white-gold", "label": "White gold", "swatch": "#e4e2dc" }
]
}
]
}The current choice is a flat map from option to variant: { "metal": "white-gold", "stone": "ruby" }.
slugis the address,labelis the name people see. Commands and starting variants use slugs; show labels to your visitors. A label may be missing — then show the slug.defaultVariantis the variant shown first; if it is missing, the first variant is.swatchis a plain CSS colour you can use for your own swatch.- A product without options reports
{ "groups": [] }: hide your selector.
Where addresses come from, and when they change
- Read them from the 3D view (as the examples do), or copy them from the Embed window → For developers. In Studio, hovering an option or choice name on the Options tab shows its address.
- An address is made from the name when the option or variant is created, and it never changes after that. Renaming keeps the address, so your page keeps working; the new name reaches visitors when you publish.
- A variant deleted and created again gets an address from its name at that moment. It can be the same as before or different (for example after a rename), so check it before you rely on it.
- Do not build addresses from names yourself: the rules for spaces, accents and duplicates are ours, and a guessed address breaks silently.
Way 1 — the <df-view> element
Copy the element from the Embed window → For developers → Copy <df-view>. It is our script and an element:
<script src="https://view.dfviews.com/embed/v1.js" async></script>
<df-view product="prd_YOUR_PRODUCT_ID" config="metal:white-gold"></df-view>Load the script as an ordinary script, not as type="module": the element takes the 3D view's address from its own script address. Give the element a size — it has none of its own; the copied code includes a <style> rule for that.
| Attribute | What it does |
|---|---|
product | The product id, prd_…. Changing it replaces the 3D view with a new one. |
config | Optional starting variants, option:variant pairs separated by commas. Set before the element is added, they are applied before the first picture. Changed later, they switch the variant without reloading. |
title | The accessible name of the 3D view (default: Interactive product view). |
| Method | What it does |
|---|---|
setConfiguration(choice) | Switches to choice, for example { metal: 'white-gold' }. Returns a promise: true — accepted; false — refused or no answer, with exactly one df-error event just before. |
getOptions() | The last reported options; { groups: [] } before df-ready. |
getConfiguration() | The last reported choice; {} before df-ready. |
| Event | detail | When |
|---|---|---|
df-ready | { options, configuration } | Once, when the 3D view is running. |
df-configuration | the current choice | After every change — from your page, from the built-in buttons, from anywhere. |
df-error | { code, message } | With every false from setConfiguration. |
df-failed | { code } | The 3D view will not start (see the table of codes below). |
How the element handles time:
- Calls made before
df-readywait and are sent in the order you made them, beforedf-readyfires. If theconfigattribute changes several times beforedf-ready, only its last value is sent. - A sent command that gets no answer within 15 seconds ends with
falseand the codetimeout. Calls waiting fordf-readyend withtimeoutafter 120 seconds without it. A product that starts On click may wait longer than that for its visitor; send your choice fromdf-readyrather than before it. - If the 3D view fails to start,
df-failedfires and waiting calls end withunavailable. - Changing
productor removing the element ends the calls of the old 3D view withbad_request; answers that arrive later from it are ignored.
Listening and switching — the four events and the method:
const view = document.querySelector('df-view')
view.addEventListener('df-ready', (event) => {
console.log('options:', event.detail.options.groups, 'selected:', event.detail.configuration)
})
view.addEventListener('df-configuration', (event) => console.log('selected now:', event.detail))
view.addEventListener('df-error', (event) => console.log('refused or no answer:', event.detail.code))
view.addEventListener('df-failed', (event) => console.log('the 3D view will not start:', event.detail.code))
// true — accepted; false — refused or no answer (the df-error event comes just before)
view.setConfiguration({ metal: 'white-gold' }).then((ok) => console.log('accepted:', ok))A complete page with your own buttons for every <df-view> on it — replace prd_YOUR_PRODUCT_ID with your product id:
Complete example: the <df-view> element with your own buttons
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Product page with its own variant buttons</title>
<style>
df-view { display: block; width: 100%; aspect-ratio: 4 / 3; }
.df-picker fieldset { border: 0; padding: 0; margin: 12px 0; }
.df-picker button[aria-pressed="true"] { font-weight: 600; outline: 2px solid currentColor; }
</style>
</head>
<body>
<df-view product="prd_YOUR_PRODUCT_ID"></df-view>
<script src="https://view.dfviews.com/embed/v1.js" async></script>
<script>
// Each <df-view> on the page gets its own buttons and its own status line.
document.querySelectorAll('df-view').forEach((view) => {
const picker = document.createElement('div')
picker.className = 'df-picker'
const status = document.createElement('p')
status.setAttribute('role', 'status')
view.after(picker, status)
// Listen right away: the events come from the 3D view's frame, which has not loaded yet.
let lastError = null
view.addEventListener('df-ready', (event) => {
draw(event.detail.options.groups)
highlight(event.detail.configuration)
})
view.addEventListener('df-configuration', (event) => highlight(event.detail))
view.addEventListener('df-error', (event) => { lastError = event.detail })
view.addEventListener('df-failed', () => {
picker.replaceChildren()
status.textContent = 'The 3D view could not start. Reload the page to try again.'
})
function draw(groups) {
picker.replaceChildren()
for (const group of groups) {
const set = document.createElement('fieldset')
const legend = document.createElement('legend')
legend.textContent = group.label || group.slug
set.append(legend)
for (const variant of group.variants) {
const button = document.createElement('button')
button.type = 'button'
button.textContent = variant.label || variant.slug
button.dataset.option = group.slug
button.dataset.variant = variant.slug
button.addEventListener('click', () => choose(group.slug, variant.slug))
set.append(button)
}
picker.append(set)
}
}
// Highlight what the 3D view reports — whoever changed it.
function highlight(configuration) {
for (const button of picker.querySelectorAll('button')) {
button.setAttribute('aria-pressed', String(configuration[button.dataset.option] === button.dataset.variant))
}
}
async function choose(option, variant) {
lastError = null
status.textContent = ''
const ok = await view.setConfiguration({ [option]: variant })
if (ok) { highlight(view.getConfiguration()); return }
// df-error arrives just before setConfiguration() resolves with false.
const code = lastError ? lastError.code : 'unknown'
if (code === 'timeout') status.textContent = 'No answer yet. The 3D view may still switch; the buttons show what it reports.'
else if (code === 'unavailable') { picker.replaceChildren(); status.textContent = 'The 3D view is not available right now.' }
else if (code === 'unknown_option') status.textContent = 'This variant is not in the published product.'
else status.textContent = 'Could not switch (' + code + ').'
}
})
</script>
</body>
</html>Way 2 — an iframe and postMessage
The In the page code is an iframe of https://view.dfviews.com/?product=prd_… (with &config=… for starting variants). Your page talks to it with postMessage.
A request:
frame.contentWindow.postMessage(
{ source: 'df-views', v: 1, id: 'q1', type: 'setConfiguration', config: { metal: 'white-gold' } },
'https://view.dfviews.com'
)The reply carries your id back:
{ source: 'df-views', v: 1, id: 'q1', type: 'result', payload: { metal: 'white-gold', stone: 'ruby' } }
{ source: 'df-views', v: 1, id: 'q1', type: 'error', payload: { code: 'unknown_option', message: '…' } }| Request | result payload |
|---|---|
getOptions | the options, as above |
getConfiguration | the current choice ({} for a product without options) |
setConfiguration with config | the whole choice after the switch |
Messages the 3D view sends on its own have no id:
type | payload | When |
|---|---|---|
ready | { options, configuration } | Once per load, when the 3D view is running. |
configuration | the current choice | After every change, whoever made it. |
failed | { code } | The 3D view will not start. |
Rules for your page:
- Listen before the frame loads. Add your
messagelistener first, then create the iframe — otherwise you can missready. A listener added later can still askgetOptionsandgetConfiguration. - Accept only your 3D view. Check
event.origin === 'https://view.dfviews.com'andevent.source === frame.contentWindow. With several 3D views on one page, the second check keeps their messages apart. - **Send to the 3D view's address, never to
'',* and not before the iframe'sloadevent: a message posted into a frame whose page has not loaded yet is lost. Requests sent afterloadbut beforereadyare held and answered once the 3D view starts — up to 32 of them; more are dropped without a reply. - Give every request your own
id(up to 128 characters) and match replies by it. A request without anidgets no reply at all. - Set your own time limit — the complete example uses 15 seconds after
ready— and treat a missing reply as an unknown outcome (see below). - Ignore message types you do not know. New types can be added within version 1; for example, the tile of Tile + window sends one to open its window.
Accepting messages — the two checks that keep 3D views apart:
const VIEW = 'https://view.dfviews.com'
window.addEventListener('message', (event) => {
if (event.origin !== VIEW || event.source !== frame.contentWindow) return // only this 3D view
const m = event.data
if (!m || m.source !== 'df-views' || m.v !== 1) return
// m.id is set: a reply to one of your requests; no id: ready, configuration or failed
})A complete page without our script — an iframe per block, its own buttons, a time limit per request. Replace prd_YOUR_PRODUCT_ID; add data-config="metal:white-gold" to a block for starting variants:
Complete example: an iframe and postMessage
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Product page with an iframe and postMessage</title>
<style>
.df-box iframe { display: block; width: 100%; aspect-ratio: 4 / 3; border: 0; }
.df-picker fieldset { border: 0; padding: 0; margin: 12px 0; }
.df-picker button[aria-pressed="true"] { font-weight: 600; outline: 2px solid currentColor; }
</style>
</head>
<body>
<div class="df-box" data-product="prd_YOUR_PRODUCT_ID"></div>
<script>
const VIEW = 'https://view.dfviews.com' // the 3D view's origin: event.origin of every message from it
const REPLY_TIMEOUT_MS = 15000 // how long to wait for a reply once the 3D view is running
document.querySelectorAll('.df-box[data-product]').forEach(connect)
function connect(box) {
const frame = document.createElement('iframe')
frame.title = 'Interactive 3D view'
frame.allow = 'fullscreen; xr-spatial-tracking'
frame.allowFullscreen = true
frame.referrerPolicy = 'strict-origin-when-cross-origin'
const url = new URL('/', VIEW)
url.searchParams.set('product', box.dataset.product)
if (box.dataset.config) url.searchParams.set('config', box.dataset.config)
frame.src = url.href
const picker = document.createElement('div')
picker.className = 'df-picker'
const status = document.createElement('p')
status.setAttribute('role', 'status')
let running = false // true after this frame's `ready`: its page is loaded and the 3D view answers
let seq = 0
const pending = new Map() // this frame's requests: id → { resolve, timer }
// 1. Listen first, then add the frame, so `ready` cannot be missed.
window.addEventListener('message', (event) => {
if (event.origin !== VIEW || event.source !== frame.contentWindow) return // only this 3D view
const m = event.data
if (!m || m.source !== 'df-views' || m.v !== 1) return
if (typeof m.id === 'string') {
const request = pending.get(m.id)
if (!request) return // a late reply after our time limit: the outcome stays unknown
pending.delete(m.id)
clearTimeout(request.timer)
request.resolve(m)
return
}
if (m.type === 'ready') {
running = true
draw(m.payload.options.groups)
highlight(m.payload.configuration)
} else if (m.type === 'configuration') {
highlight(m.payload) // what is selected now, not the answer to any request
} else if (m.type === 'failed') {
stop('The 3D view could not start. Reload the page to try again.')
}
})
box.append(frame, picker, status)
// 2. Send only to a running 3D view, to its origin, with an id; null means no answer in time.
function request(message) {
const id = 'q' + (++seq)
return new Promise((resolve) => {
const timer = setTimeout(() => { pending.delete(id); resolve(null) }, REPLY_TIMEOUT_MS)
pending.set(id, { resolve, timer })
frame.contentWindow.postMessage({ source: 'df-views', v: 1, id, ...message }, VIEW)
})
}
async function choose(option, variant) {
if (!running) return
status.textContent = ''
const reply = await request({ type: 'setConfiguration', config: { [option]: variant } })
if (reply === null) {
status.textContent = 'No answer yet. The 3D view may still switch; the buttons show what it reports.'
return
}
if (reply.type === 'result') { highlight(reply.payload); return }
const code = reply.payload && reply.payload.code
if (code === 'unavailable') stop('The 3D view is not available right now.')
else if (code === 'unknown_option') status.textContent = 'This variant is not in the published product.'
else status.textContent = 'Could not switch (' + code + ').'
}
function stop(text) {
running = false
picker.replaceChildren()
status.textContent = text
}
function draw(groups) {
picker.replaceChildren()
for (const group of groups) {
const set = document.createElement('fieldset')
const legend = document.createElement('legend')
legend.textContent = group.label || group.slug
set.append(legend)
for (const variant of group.variants) {
const button = document.createElement('button')
button.type = 'button'
button.textContent = variant.label || variant.slug
button.dataset.option = group.slug
button.dataset.variant = variant.slug
button.addEventListener('click', () => choose(group.slug, variant.slug))
set.append(button)
}
picker.append(set)
}
}
function highlight(configuration) {
for (const button of picker.querySelectorAll('button')) {
button.setAttribute('aria-pressed', String(configuration[button.dataset.option] === button.dataset.variant))
}
}
}
</script>
</body>
</html>Switching, replies and what they mean
setConfigurationmerges:{ metal: 'white-gold' }changes the metal and leaves the other options as they are.- The whole command is checked first. An unknown option or variant gives
unknown_option, and nothing changes — not the choice, not the picture, and noconfigurationevent. - A command that changes nothing still gets
result, without aconfigurationevent. - Several commands in a row are answered in the order they were sent; the last valid one wins. Switching does not move the camera.
resultmeans accepted and applied to the scene — not that the final picture is on screen. Textures of the new variant may still be loading, and there is no separate signal for that.- The
configurationevent has noid. It tells you what is selected now, not which command caused it — the visitor may have clicked a built-in button. Highlight your controls from it; judge your own commands by their replies. - No reply in time is an unknown outcome, neither a refusal nor a success: the 3D view may still apply the command later. Do not show "not changed" or "done"; show what
configurationreports, and do not resend in a loop. - Starting variants in the
configattribute or&config=are applied before the first picture. Pairs that do not exist in the published product are skipped, and those options start on their default;readyreports what was really applied.
Codes
| Code | Meaning | What to do |
|---|---|---|
unknown_option | The command names an option or variant the product does not have. Nothing changed. | Fix the address. |
not_supported | The product has no options, or it was published by a build that predates them. | Hide your selector; publishing the product again may help. |
bad_request | The message is malformed: no id, unknown type, or a config that is not a flat map of addresses (letters, digits, - and _, up to 64 characters). With <df-view> it also ends calls of a removed or replaced 3D view. | Check the message. |
bad_version | Unknown protocol version. | Use v: 1. |
unavailable | The 3D view cannot answer on this page load: it failed to start (you also get failed), or it is paused, for example when the organization's storefront views run out. | Show your own fallback; it does not recover without a page reload. |
timeout | <df-view> only: no reply in time. | An unknown outcome — follow df-configuration. |
Codes of failed / df-failed:
| Code | Meaning |
|---|---|
not_licensed | Your website is not in Settings → Embed domains (see Embed). |
product_not_found / bad_product_id | No published product with this id. |
product_removed | The product was taken off the storefront. |
| any other code | The 3D view could not load. |
Several 3D views on one page
Every 3D view is independent: its own options, choice and replies. The complete examples connect every block on the page separately, so a command to one never reaches another — even for the same product shown twice. Code copied from the Embed window is independent per copy as well. With your own iframes keep one set of pending requests per frame and always check event.source. Each frame loads its own copy of the product.
How storefront views are counted
The view counter counts viewing sessions the storefront issues, not 3D starts. What that means for your page today:
- A session is issued when the 3D view's frame starts loading and the server accepts it. That is one storefront view.
- A frame refused before the session is issued is not counted: a website that is not in Settings → Embed domains (
not_licensed), or a product that does not exist. A failure after the session was issued — for examplefailedwith a loading code such asscene_failedorruntime_load— does not cancel the view. - A product that starts On click or When seen gets its session when its frame loads — before the visitor clicks or sees it.
- Tile + window: the tile and the window opened from it are separate frames with separate sessions — the tile counts once when it loads, and every opening of the window counts again.
- The code from the Embed window loads its iframe lazily (
loading="lazy"): a block far below the visible part of the page loads, and counts, only when the visitor scrolls near it.<df-view>creates its frame as soon as the element is on the page. - Repeats of one start are not counted twice. Each frame load gets its own attempt key, and the frame sends the same key when it repeats the request after a network failure. While the session started by that attempt is still valid, the repeat gets the same session and is not counted again. A new frame load — a new block, the tile, each opening of the window, a page reload — is a new attempt and counts again.
- Limits. Recognising a repeat depends on the server's view counter answering. If it does not answer, the 3D view still opens; in that case we do not promise that the repeat is recognised as the same start or that its reply is identical (the token may carry a later expiry time). A page that was already open when the storefront code was updated keeps the earlier code, without attempt keys, until it is reloaded.
Your own messages — getOptions, setConfiguration and the rest — never count as views.
Testing your page
- Serve the page from a local web server, for example
http://localhost:8000:localhostis always allowed, so the product opens before you list your website. A page opened as a file from your disk has no origin, and messages from the 3D view cannot be addressed to it. - Use the product id and the address exactly as Studio gives them: a product opens only through the 3D view address it was published for.
- When you move to your real website, list it in Settings → Embed domains (see Embed).