本指南介绍如何使用 Cloudflare RealtimeKit Core SDK 构建自定义插件并在会议中运行它。
自定义插件是您向 SDK 注册的 DOM 元素。当参与者激活该插件时,RealtimeKit 会在会话中为每个人激活该插件,并将其渲染在会议布局中。
This page is not available for the Mobile platform.
Web Mobile
React Web Components Angular
本页面基于初始化 SDK 和插件 指南。请先阅读这些内容。
示例假设您已经导入了必要的包并初始化了 SDK。
插件包含两个部分:
组件(component) :一个包含您插件 UI 和逻辑的 DOM 元素(HTMLElement)。
注册(registration) :您传递给 SDK 的配置对象,以便其列出、激活并渲染该组件。
RealtimeKit 会在整个会话中同步激活状态。要在参与者之间共享插件数据,请使用协作存储(collaborative stores) 。
插件组件必须是 HTMLElement。可以直接将其构建为自定义元素,或者创建一个容器元素并将您的框架组件树挂载到其中。
将您的插件定义为自定义元素,然后创建一个实例以作为 component 传递。
my-counter-plugin.ts ts class MyCounterPlugin extends HTMLElement {
connectedCallback () {
this .innerHTML = `
<div class="counter">
<button id="increment">This is a counter plugin</button>
<span id="value">0</span>
</div>
` ;
}
}
customElements. define ( "my-counter-plugin" , MyCounterPlugin);
const pluginElement = document. createElement ( "my-counter-plugin" ); 创建一个容器元素并将您的组件树挂载到其中。将容器作为 component 传递。
counter-plugin.tsx tsx import { createRoot } from "react-dom/client" ;
function CounterPlugin () {
return < div className = "counter" >This is a counter plugin</ div >;
}
const pluginElement = document. createElement ( "div" );
createRoot (pluginElement). render (< CounterPlugin />); 创建一个容器元素并将您的组件树挂载到其中。将容器作为 component 传递。
counter-plugin.ts ts import {
createComponent,
ApplicationRef,
EnvironmentInjector,
} from "@angular/core" ;
import { CounterPluginComponent } from "./counter-plugin.component" ;
const pluginElement = document. createElement ( "div" );
const componentRef = createComponent (CounterPluginComponent, {
environmentInjector: this .injector,
hostElement: pluginElement,
});
this .appRef. attachView (componentRef.hostView);
在初始化 SDK 时注册会话中可用的插件。将插件配置数组作为 defaults.plugins 传递,并使用您在步骤 1 中创建的 pluginElement 作为 component。
RealtimeKitClient. init ({
authToken: "<auth_token>" ,
defaults: {
plugins: [
{
id: "counter" ,
name: "Counter" ,
icon: "https://example.com/counter.png" ,
permissions: {
canActivate: true ,
canDeactivate: true ,
},
component: pluginElement,
},
],
},
});
有关每个配置字段的描述,请参阅注册插件 。
注册后,插件将显示在 meeting.plugins.all 中。激活它以使其在会话中对所有人均有效。
const plugin = meeting.plugins.all. get (pluginId);
await plugin. activate (); const plugins = useRealtimeKitSelector (( m ) => m.plugins);
const plugin = plugins.all. get (pluginId);
await plugin. activate (); 说明
如果您使用 UI Kit,插件组件将为您处理激活和渲染。
Plugin 对象会随着其状态的变化而触发事件。当其被激活或停用时,使用这些事件来设置或销毁您的组件。
const plugin = meeting.plugins.all. get (pluginId);
plugin. on ( "enabled" , () => {
// 插件对本地参与者生效
});
plugin. on ( "closed" , () => {
// 插件对本地参与者已停用
});
有关插件事件的完整列表,请参阅监听插件事件 。
每个参与者运行他们自己的插件组件副本,因此您需要一种在他们之间共享状态的方法。RealtimeKit 提供了两个内置的实时通信选项:
对于需求简单的插件,这些内置的 API 足以处理您的协作逻辑。
// 为您的插件创建或获取存储
const store = meeting.stores. create ( "counter" );
// 为所有参与者更新一个值
await store. set ( "value" , 1 );
// 对来自任何参与者的更新作出反应
store. subscribe ( "value" , ({ value }) => {
document. querySelector ( "#value" ).textContent = value;
});
为了获得更丰富、功能更全的协作体验,您可以将您的插件与专用的第三方框架配对: