Message API/docs/getting-started/iframe-init

Initialize Canvas

Embed the Canvas iframe and dispatch the first view payload.

Overview

Set the Canvas URL, mount the iframe, and send a view message once it loads.

  • Keep the viewer origin and URL in a single configuration module.
  • Wait for the iframe load event before posting messages.
  • Send a `view` payload with a file URL to bootstrap the session.

Define the Canvas URL

Define the Canvas URL once and reuse it across viewer sessions.

javascript
// Centralize the Canvas URL for reuse.
const CANVAS_URL = 'https://your-canvas-domain.com'
const viewerSrc = CANVAS_URL
Define the Canvas URL

Initialize the iframe

Create the iframe, attach it to the DOM, and wait for the load event before sending messages.

javascript
const viewerOrigin = getViewerOrigin()
const viewerSrc = CANVAS_URL

const iframe = document.querySelector('[data-viewer-iframe]')
if (!iframe) {
  throw new Error('Canvas iframe not found')
}

// Load the viewer UI.
iframe.src = viewerSrc
iframe.addEventListener('load', () => {
  // Send the first view payload after load.
  iframe.contentWindow?.postMessage(
    {
      type: 'view',
      payload: {
        fileUrl: '<YOUR_FILE_URL>',
        },
    },
    viewerOrigin,
  )
})
Initialize the iframe

Type the payload (TypeScript)

Reuse a typed payload shape to keep viewer messages consistent.

typescript
type ViewMessage = {
  type: 'view'
  payload: {
    fileUrl: string
  }
}

const viewerOrigin = getViewerOrigin()
const iframe = document.querySelector('[data-viewer-iframe]') as HTMLIFrameElement | null

const message: ViewMessage = {
  type: 'view',
  payload: {
    fileUrl: '<YOUR_FILE_URL>',
  },
}

// Post the payload once the iframe is ready.
iframe?.contentWindow?.postMessage(message, viewerOrigin)
Type the payload (TypeScript)

Handle progress events

Use progressStart and progressEnd to drive loading UI while the viewer prepares files.

javascript
window.addEventListener('message', (event) => {
  if (event.origin !== viewerOrigin) return

  if (event.data?.type === 'progressStart') {
    setIsLoading(true)
  }

  if (event.data?.type === 'progressEnd') {
    setIsLoading(false)
  }
})
Handle progress events

Complete Implementation

A full example with configuration, iframe lifecycle, and the initial view message.

javascript
// CONFIGURATION
const CANVAS_URL = 'https://your-canvas-domain.com'
const viewerOrigin = getViewerOrigin()

// IFRAME SETUP
const iframe = document.querySelector('[data-viewer-iframe]')
if (!iframe) {
  throw new Error('Canvas iframe not found')
}

// Load the viewer UI.
iframe.src = CANVAS_URL

// Wait for iframe load before sending any messages.
iframe.addEventListener('load', () => {
  iframe.contentWindow?.postMessage(
    {
      type: 'view',
      payload: {
        fileUrl: '<YOUR_FILE_URL>',
      },
    },
    viewerOrigin,
  )
})
Complete Implementation