> Listen to step changes from an embedded LiveDemo and move it to any step from your page with postMessage.

Canonical: https://livedemo.ai/docs/share/embed-events/

# Embed events

An [embedded](https://livedemo.ai/docs/share/embed-on-website/) demo talks to your page with `postMessage`.

## Listen to step changes

Every time the viewer reaches a step, the demo sends `step_index_changed`:

```js
window.addEventListener('message', (event) => {
    if (event.origin !== 'https://story-api.livedemo.ai') return
    if (event.data && event.data.type === 'step_index_changed') {
        const { stepNumber } = event.data.state
        console.log('Viewer is on step', stepNumber)
    }
})
```

`stepNumber` starts at 1. Always check `event.origin`.

## Listen to analytics events

The demo also sends `livedemo:event` messages for views, steps, completion, button clicks and leads:

```js
window.addEventListener('message', (event) => {
    if (event.origin !== 'https://story-api.livedemo.ai') return
    if (event.data?.type !== 'livedemo:event') return
    console.log(event.data.name, event.data.properties)
})
```

`name` is one of `livedemo_demo_view`, `livedemo_step_view`, `livedemo_demo_complete`, `livedemo_cta_click` or `livedemo_lead_captured`. See [Google Analytics](https://livedemo.ai/docs/analytics/google-analytics/#with-a-plain-embed) for the properties.

## Move the demo to a step

```js
const iframe = document.querySelector('iframe')
iframe.contentWindow.postMessage({ type: 'changeStep', stepNumber: 3 }, 'https://story-api.livedemo.ai')
```

## What to build with it

- Send events to your analytics tool. See [Google Analytics](https://livedemo.ai/docs/analytics/google-analytics/) and [Segment](https://livedemo.ai/docs/analytics/segment/).
- Show a "Book a demo" button next to the embed when the viewer reaches the last step.
- Build your own chapter menu: buttons on your page that call `changeStep`.
- Sync the demo with the text of a help article as the reader scrolls.

---

Next: [Preview & fullscreen](https://livedemo.ai/docs/share/preview-and-fullscreen/)
