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.

Two ways use the same protocol (version 1). Pick one per 3D view:

WayBest for
The <df-view> elementMost pages: one script tag, an element, events and a method that returns true or false.
An iframe and postMessagePages that cannot load our script, or that already manage their own frames.

What the 3D view reports

The options come from the published product:

JSON
{
  "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" }.

Where addresses come from, and when they change

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:

HTML
<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.

AttributeWhat it does
productThe product id, prd_…. Changing it replaces the 3D view with a new one.
configOptional 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.
titleThe accessible name of the 3D view (default: Interactive product view).
MethodWhat 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.
EventdetailWhen
df-ready{ options, configuration }Once, when the 3D view is running.
df-configurationthe current choiceAfter 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:

Listening and switching — the four events and the method:

JavaScript
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
HTML
<!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:

JavaScript
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:

JavaScript
{ 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: '…' } }

Requestresult payload
getOptionsthe options, as above
getConfigurationthe current choice ({} for a product without options)
setConfiguration with configthe whole choice after the switch

Messages the 3D view sends on its own have no id:

typepayloadWhen
ready{ options, configuration }Once per load, when the 3D view is running.
configurationthe current choiceAfter every change, whoever made it.
failed{ code }The 3D view will not start.

Rules for your page:

  1. Listen before the frame loads. Add your message listener first, then create the iframe — otherwise you can miss ready. A listener added later can still ask getOptions and getConfiguration.
  2. Accept only your 3D view. Check event.origin === 'https://view.dfviews.com' and event.source === frame.contentWindow. With several 3D views on one page, the second check keeps their messages apart.
  3. **Send to the 3D view's address, never to '',* and not before the iframe's load event: a message posted into a frame whose page has not loaded yet is lost. Requests sent after load but before ready are held and answered once the 3D view starts — up to 32 of them; more are dropped without a reply.
  4. Give every request your own id (up to 128 characters) and match replies by it. A request without an id gets no reply at all.
  5. Set your own time limit — the complete example uses 15 seconds after ready — and treat a missing reply as an unknown outcome (see below).
  6. 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:

JavaScript
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
HTML
<!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

Codes

CodeMeaningWhat to do
unknown_optionThe command names an option or variant the product does not have. Nothing changed.Fix the address.
not_supportedThe product has no options, or it was published by a build that predates them.Hide your selector; publishing the product again may help.
bad_requestThe 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_versionUnknown protocol version.Use v: 1.
unavailableThe 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:

CodeMeaning
not_licensedYour website is not in Settings → Embed domains (see Embed).
product_not_found / bad_product_idNo published product with this id.
product_removedThe product was taken off the storefront.
any other codeThe 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:

Your own messages — getOptions, setConfiguration and the rest — never count as views.

Testing your page