插件与宿主通信
插件与 Such 宿主之间的通信方式与 API 参考
插件与宿主通信
插件与 Such 宿主之间的通信有四种方式:
通信方式总览
| 方式 | 方向 | 用途 |
|---|---|---|
console.log/warn/error | 插件 → 宿主 | 输出日志到宿主控制台 |
window.notify(message, type?) | 插件 → 宿主 | 发送桌面通知给用户 |
this.emit(eventName, ...args) | 插件 → 宿主 | 触发自定义事件 |
this.setProps(partialProps) | 插件 → 宿主 | 更新 UI 状态,触发界面重渲染 |
console — 日志输出
插件中的 console.log、console.warn、console.error 会被宿主拦截并转发到渲染进程。
initialization() {
console.log('插件启动') // → 宿主日志 [INFO]
console.warn('建议更新') // → 宿主日志 [WARN]
console.error('操作失败') // → 宿主日志 [ERROR]
}日志最终显示位置:
- Such 主进程控制台(开发模式)
- 插件详情页的日志面板
ℹ️ 插件中的
console不是浏览器原生 console,是宿主注入的代理对象。因此部分浏览器特有的 console 方法(如console.table、console.group)可能不可用。
window.notify — 桌面通知
向用户发送桌面通知消息。
window.notify(message: string, type?: 'success' | 'error' | 'warning' | 'info'): void| type | 说明 | 图标 |
|---|---|---|
success | 成功通知 | 绿色勾 |
error | 错误通知 | 红色叉 |
warning | 警告通知 | 橙色叹号 |
info | 信息通知(默认) | 蓝色 i |
// 成功
window.notify('NCM 文件转换成功,已保存到音乐文件夹', 'success')
// 错误
window.notify('转换失败:ncmdump 未安装', 'error')
// 警告
window.notify('您的插件版本已过期,建议更新', 'warning')
// 普通信息
window.notify('正在检查更新...', 'info')⚠️
window.notify是同步方法,不会阻塞也不返回 Promise。
this.emit — 事件触发
向宿主触发自定义事件。宿主可监听这些事件做出响应(如打开文件选择器)。
this.emit(eventName: string, ...args: any[]): void示例:
// 触发文件选择事件
this.emit('browse')
// 触发带参数的事件
this.emit('fileSelected', 'C:\\Users\\xxx\\song.ncm')
// 触发提交事件
this.emit('submit', { playlistId: '123', cookie: 'xxx' })ℹ️ emit 通常与
uiSchema中的action字段配合使用,实现 UI 交互事件传递。
this.setProps — UI 状态更新
更新插件 props 并触发 UI 重渲染。这是 JSON UI Schema 和 JSX UI 的核心更新机制。
this.setProps(partialProps: Record<string, any>): voidasync startProcess() {
// 更新进度和状态
this.setProps({ progress: 0, status: 'processing' })
for (let i = 1; i <= 10; i++) {
await sleep(500)
this.setProps({ progress: i * 10 })
}
this.setProps({ progress: 100, status: 'done' })
window.notify('处理完成!', 'success')
}ℹ️
setProps是浅合并(shallow merge),只更新传入的 key,不影响其他 props 属性。
通信方向总结
┌──────────────┐ ┌──────────────┐
│ 插件代码 │ │ Such 宿主 │
│ │ console.log ────→ │ │
│ │ window.notify ──→ │ │
│ │ this.emit ──────→ │ │
│ │ this.setProps ──→ │ │
│ │ │ │
│ │ ←──── IPC ────── │ (确认弹窗等) │
└──────────────┘ └──────────────┘插件到宿主的通信全部通过上述四种 API。宿主到插件的通信通过调用插件的注册方法实现(如 initialization() 由宿主调用,checkUpdate() 由宿主触发)。