Skip to content

Embedding the Offline HTML Viewer with the Host Bridge ​

Exported offline HTML viewers (chtml / @mlightcad/cad-html-plugin) are self-contained pages. When you embed one in your own web app, you often want the parent page to drive navigation, layers, measurement, markup, and settings — while keeping drawing and file dialogs inside the iframe.

The HTML viewer host bridge is an opt-in, origin-validated postMessage channel for that. Standalone exports are unchanged: omit the option and the bridge never starts.

This guide is for host-app developers. For packaging and static hosting of multi-file ACEX packages, see Build a Cloud DWG Web Viewer. Protocol types live in @mlightcad/cad-html-core (AcExHtmlHostBridge.ts).

Online demo ​

Try a parent page with host-owned chrome against a bridge-enabled canteen HTML export:

👉 HTML viewer host bridge demo

The gallery builds canteen-bridge.html in CI with hostBridge.parentOrigin set to https://mlightcad.com (GitHub Pages redirects *.github.io there, so that is the browser origin). Locally, regenerate with HOST_BRIDGE_PARENT_ORIGIN=http://localhost:3000 pnpm export:demo-html from packages/cad-demo-gallery.


When to use it ​

Use the host bridge when:

  • Your product shell owns the chrome (ribbon, side panels, mobile bars) and the viewer is only the canvas + drawers inside an iframe
  • You need to sync theme, locale, layers, or layout selection with the surrounding app
  • You want to trigger measure / markup modes from host UI without reimplementing the offline viewer

Prefer a plain standalone HTML (or an iframe without the bridge) when users open the file by double-click / email, or when you do not need programmatic control.


Architecture ​

Important properties:

  • Opt-in. Only exports that pass hostBridge: { parentOrigin } embed a #mlcad-host-bridge JSON config. Without it, no listener is registered.
  • Exact origin. parentOrigin must be an exact http: / https: origin (scheme + host + non-default port). Paths, wildcards, credentials, and opaque null origins are rejected at export and at runtime.
  • Immediate parent only. The viewer accepts messages only from window.parent with that origin. Sibling frames cannot drive the bridge.
  • Allow-listed commands. Unknown or malformed commands return invalid-command. Drawing / file pickers stay in the iframe; import/export commands return awaiting-user so the user confirms inside the viewer.

1. Enable the bridge at export time ​

Pass the parent page’s origin when exporting. The same option works for single-file HTML and multi-file packages.

Browser plugin (chtml / AcApHtmlConvertor) ​

ts
import type { AcApHtmlExportOptions } from '@mlightcad/cad-html-plugin'

const options: AcApHtmlExportOptions = {
  exportFormat: 'single', // or 'multi'
  viewerMode: 'measure',
  hostBridge: {
    // Exact origin of the page that will host the iframe
    parentOrigin: 'https://app.example.com'
  }
}

Headless exporter (@mlightcad/cad-html-exporter) ​

ts
await exportFileToHtml(inputPath, outputPath, {
  hostBridge: { parentOrigin: 'https://app.example.com' }
})

Include the non-default port when the host is served locally, for example http://127.0.0.1:5173. https://app.example.com/ (trailing slash only) is normalized to https://app.example.com; anything else in the path is an error.

The packager writes a safe JSON script into the HTML:

html
<script id="mlcad-host-bridge" type="application/json">
  {"parentOrigin":"https://app.example.com"}
</script>

2. Embed the viewer and open the channel ​

Host the exported viewer.html (or single .html file) on its own origin if you can — that keeps cookie / CSP boundaries clear. Embed it from the trusted parent:

html
<iframe
  id="viewer"
  src="https://cdn.example.com/drawings/demo/viewer.html?toolbar=host"
  style="width:100%;height:100%;border:0"
></iframe>

?toolbar=host is optional. After the parent sends a successful hello (or the first accepted command), the viewer removes the built-in offline toolbar and shortcut chrome so your shell can own those controls. Listening for the initial ready alone is not enough — send hello once the iframe has loaded. Drawers (layers, measure, markup) still open inside the iframe when the host sends panel commands. Omit the query (or use ?toolbar=native) to keep the offline toolbar while still using the bridge.

Minimal host glue:

ts
import {
  ACEX_HTML_HOST_BRIDGE_CHANNEL,
  ACEX_HTML_HOST_BRIDGE_VERSION,
  type AcExHtmlHostCommand,
  type AcExHtmlHostResponse,
  type AcExHtmlHostState
} from '@mlightcad/cad-html-core'

const CHANNEL = ACEX_HTML_HOST_BRIDGE_CHANNEL
const VERSION = ACEX_HTML_HOST_BRIDGE_VERSION

const iframe = document.querySelector<HTMLIFrameElement>('#viewer')!
const viewerOrigin = new URL(iframe.src).origin

function post(message: object) {
  iframe.contentWindow!.postMessage(message, viewerOrigin)
}

window.addEventListener('message', (event: MessageEvent<AcExHtmlHostResponse>) => {
  if (event.source !== iframe.contentWindow) return
  if (event.origin !== viewerOrigin) return
  if (event.data?.channel !== CHANNEL) return

  switch (event.data.type) {
    case 'ready':
    case 'state-changed':
      renderHostUi(event.data.state)
      break
    case 'result':
      if (event.data.ok) renderHostUi(event.data.state)
      else console.warn(event.data.error)
      break
    case 'error':
      console.warn(event.data.error)
      break
  }
})

// Optional handshake after the iframe has painted; the viewer also sends
// `ready` once on startup when the access gate is open.
post({ channel: CHANNEL, version: VERSION, type: 'hello' })

function sendCommand(command: AcExHtmlHostCommand, requestId = crypto.randomUUID()) {
  post({ channel: CHANNEL, version: VERSION, type: 'command', requestId, command })
}

function renderHostUi(_state: AcExHtmlHostState) {
  // Drive your ribbon / status bar from the serializable state snapshot.
}

Always target viewerOrigin in postMessage (never '*'). Always verify event.source and event.origin on the way back.


3. Message protocol ​

DirectiontypeMeaning
Host → viewerhelloAsk for a fresh ready snapshot (and mark the parent connected)
Host → viewercommandRun one allow-listed operation; requires requestId (1–128 chars)
Viewer → hostreadyBridge is up (or hello answered); includes state
Viewer → hostresultCommand finished: ok: true with outcome + state, or ok: false with error
Viewer → hoststate-changedUser or UI changed something after connect; includes state
Viewer → hosterrorProtocol / access problem not tied to a request

Every message carries:

ts
{
  channel: 'mlightcad-html-viewer', // ACEX_HTML_HOST_BRIDGE_CHANNEL
  version: 1                       // ACEX_HTML_HOST_BRIDGE_VERSION
}

Unsupported versions are rejected with invalid-message.

Successful outcome values ​

ValueMeaning
doneCommand finished inside the viewer
awaiting-userA file / color / text dialog opened in the iframe; finish there

While a dialog is open, further file actions typically fail with busy.

Error codes ​

CodeTypical cause
invalid-messageWrong version, missing requestId, …
invalid-commandUnknown command shape or bad argument
unsupportedFeature not available in this export (e.g. view-only mode)
not-readyGeometry / OSNAP / selection not ready yet
busyAnother modal action is already open
access-blockedPassword / expiry gate still closed
operation-failedUnexpected runtime failure

Commands are serialized on the viewer side: a layout switch finishes before the next command runs.


4. Command catalog ​

CommandNotes
{ type: 'get-state' }Return current AcExHtmlHostState
{ type: 'set-navigation', mode }'select' | 'pan' | 'zoom-window'
{ type: 'zoom', mode }'saved' | 'extents' | 'smart' | 'in' | 'out'
{ type: 'cancel' }Cancel the active tool
{ type: 'layer-panel', open }Open / close the layer drawer
{ type: 'set-layer', name, visible }Toggle one layer
{ type: 'set-all-layers', visible }Show / hide every layer
{ type: 'zoom-layer', name }Zoom to a layer’s extents
{ type: 'set-layout', id }Switch layout by block-table record id
{ type: 'measure-mode', mode }'distance' | 'continuous' | 'angle' | 'arc' | 'radius' | 'area' | 'coordinate'
{ type: 'measure-panel', open }Measure drawer
{ type: 'measure-visible', visible }Show / hide measure graphics
{ type: 'measure-clear' }Clear measurements
{ type: 'measure-import' } / 'measure-export'File dialog in the iframe → awaiting-user
{ type: 'markup-mode', mode }'cloud' | 'rect' | 'circle' | 'callout' | 'arrow' | 'text' | 'stamp'
{ type: 'markup-panel', open }Markup / review drawer
{ type: 'markup-visible', visible }Show / hide markups
{ type: 'markup-clear' }Clear markups
{ type: 'markup-import' } / 'markup-export'File dialog in the iframe → awaiting-user
{ type: 'undo' } / 'redo' / 'erase'History / erase selection
{ type: 'selection-color' } / 'selection-text-height'Opens in-iframe editors → awaiting-user
{ type: 'set-theme', theme }'dark' | 'light'
{ type: 'toggle-background' }Swap canvas ink / background
{ type: 'set-locale', locale }Offline viewer locale (en, zh, …)
{ type: 'set-simulated-mouse', enabled }Touch simulated-mouse mode
{ type: 'set-ortho', enabled }Ortho mode
{ type: 'polar-panel', open }Polar angle panel
{ type: 'set-polar', angle }number from the polar increment list, or null to clear

Measure and markup commands require viewerMode: 'measure' (the default). View-only exports reject them with unsupported.


5. State snapshot ​

AcExHtmlHostState is a JSON-serializable summary suitable for binding host UI:

ts
{
  viewerMode: 'view' | 'measure'
  readiness: { geometry: boolean; osnap: boolean }
  exportLayouts: boolean
  activeLayoutId: string
  layouts: { id: string; name: string; isModelSpace: boolean }[]
  layers: { name: string; visible: boolean }[]
  layerPanelOpen: boolean
  navigation: 'select' | 'pan' | 'zoom-window'
  camera: { centerX: number; centerY: number; zoom: number }
  measurement: { mode; visible; panelOpen } | null
  markup: { mode; visible; panelOpen } | null
  history: { canUndo: boolean; canRedo: boolean; canErase: boolean }
  settings: {
    theme: 'dark' | 'light'
    locale: string
    simulatedMouse: boolean
    backgroundSwapped: boolean
    ortho: boolean
    polar: boolean
    polarAngle: number | null
    polarPanelOpen: boolean
  }
}

Wait until readiness.geometry (and readiness.osnap when measuring) is true before issuing interactive tools. Layout switches may temporarily clear readiness while chunks load.


6. Security checklist ​

  • Export with the production parent origin — not * and not a staging origin you later forget to rotate
  • Host and viewer origins may differ; the bridge pins the parent origin into the HTML at export time. That embedded #mlcad-host-bridge value is a client-side trust anchor: anyone who can rewrite the static HTML (CDN compromise, bad deploy, MITM) can retarget parentOrigin. Protect the artifact (private storage, signed URLs, integrity checks) the same way you protect other published drawing packages
  • Re-export (or rebuild packages) when the parent origin changes
  • Do not forward untrusted third-party messages into the iframe
  • Password-protected / expired viewers report access-blocked until the gate opens; treat that as a hard stop for host automation
  • Drawing and file selection never leave the iframe — that keeps file pickers under the viewer’s origin and user gesture
  • Commands are serialized: a slow set-layout blocks later commands including get-state. Prefer waiting on each result instead of polling during layout loads

Unauthorized parents receive no bridge traffic. The offline toolbar stays visible so the drawing remains usable when opened outside your shell.


7. End-to-end example ​

ts
// 1) Export once (CI / server)
await exportFileToHtml('plan.dwg', 'out/viewer.html', {
  exportFormat: 'single',
  viewerMode: 'measure',
  hostBridge: { parentOrigin: 'https://app.example.com' }
})

// 2) Parent page at https://app.example.com
const iframe = document.querySelector('iframe')!
const origin = new URL(iframe.src).origin

iframe.addEventListener('load', () => {
  iframe.contentWindow!.postMessage(
    {
      channel: 'mlightcad-html-viewer',
      version: 1,
      type: 'hello'
    },
    origin
  )
})

document.getElementById('btn-extents')!.onclick = () => {
  iframe.contentWindow!.postMessage(
    {
      channel: 'mlightcad-html-viewer',
      version: 1,
      type: 'command',
      requestId: crypto.randomUUID(),
      command: { type: 'zoom', mode: 'extents' }
    },
    origin
  )
}

Browser coverage for the protocol lives in packages/cad-editor-demo/e2e/tests/html-host-bridge.spec.ts.