# 起步

直接在应用中嵌入我们预设的 HTML5 编辑页面,快速接入协同编辑能力!

# 了解

具体架构和交互流程可参考下图:

H5接入说明

# 流程

# 准备工作

在 HTML 中准备一个 iframe,比如:

<body>
  <iframe id="editor" frameborder="0" width="1024" height="768"></iframe>
</body>

# 加载编辑页面

通过 fid 和 token 生成编辑页面的 URL,然后使用 iframe 进行加载。

const iframeElement = document.getElementById('editor')
const url = 'http://open.iflydocs.com/editor/editor.html'
const fid = '<YOUR FID>'
const token = '<YOUR TOKEN>'
iframeElement.src = `${url}?fid=${fid}&token=${token}`

# 初始化

通过监听 iframe 元素的 load 事件,发送 set-appId 消息,进行初始化。通过传入 APPID,我们可以获取后台绑定的 iframe 宿主页面域名白名单,判断编辑器在当前页面是否可用。

iframeElement.addEventListener('load', () => {
  iframeElement.contentWindow.postMessage(
    {
      action: 'set-appId',
      data: {
        appId: '<YOUR APPID>',
      },
    },
    '*'
  )
})

# 消息通信

初始化完成之后,可以通过监听 iframe 元素的 message 事件实现和 iframe 的通信。

window.addEventListener('message', (event) => {
  const action = event.data.action
  console.log('iframe message action:', action)
})

消息分为两种,接口消息和回调消息。

接口消息指应用主动向 iframe 元素传递数据的消息,上一节的 set-appId 消息就是一个接口消息。更多的接口消息详见 接口消息说明

回调消息指应用从 iframe 接收到的消息,如编辑器内容变更等。回调消息通过 event.data.action 字段进行区分,event.data.data 字段会携带相关数据。更多的回调消息详见 回调消息说明