Skip to content

H5 Overlay 示例

当 H5 客户端运行在允许访问 127.0.0.1 WebSocket 的本机环境时,可以直接连接。

典型用途:

  • 本机 browser source overlay。
  • 本机控制面板。
  • 开发者调试页。

浏览器示例

html
<button id="connect">Connect</button>
<pre id="log"></pre>

<script type="module">
  const log = document.querySelector('#log')

  function print(message) {
    log.textContent += `${message}\n`
  }

  async function connectCandidate(port) {
    const socket = new WebSocket(`ws://127.0.0.1:${port}/v1/third-party`)

    return new Promise((resolve) => {
      const timer = setTimeout(() => {
        socket.close()
        resolve(null)
      }, 3000)

      socket.addEventListener(
        'message',
        (event) => {
          clearTimeout(timer)
          const hello = JSON.parse(event.data)
          if (
            hello.type === 'SERVER_HELLO' &&
            hello.product === 'tiktok_live_studio' &&
            hello.channel === 'third-party-im'
          ) {
            resolve(socket)
          } else {
            socket.close()
            resolve(null)
          }
        },
        { once: true }
      )

      socket.addEventListener('error', () => {
        clearTimeout(timer)
        resolve(null)
      })
    })
  }

  async function connect() {
    for (let port = 30000; port <= 30015; port += 1) {
      const socket = await connectCandidate(port)
      if (!socket) continue

      socket.send(JSON.stringify({
        type: 'AUTH',
        app_id: 'your_app_id',
        key_id: 'your_key_id',
        secret: 'your_secret',
        version: '1.0.0'
      }))

      socket.addEventListener('message', (event) => {
        const message = JSON.parse(event.data)
        print(JSON.stringify(message, null, 2))
      })

      print(`connected to ${port}`)
      return
    }

    print('LIVE Studio endpoint not found')
  }

  document.querySelector('#connect').addEventListener('click', connect)
</script>

安全注意

  • 不要把生产凭证打进公开的 web 资源。
  • 带凭证的接入优先使用本机打包客户端或受控开发工具。
  • 不要通过远程代理暴露本机 WebSocket 连接。