0.0.1 • Published 12 months ago
@neural-nexus/portal-channel v0.0.1
About
@neural-nexus/portal-channel
Feature
- 🤝 支持 iframe 及非 iframe 执行环境
- 📢 支持不同执行环境之间的广播通信
- 🚀 支持 iframe 的监听句柄不受限制
install
step 1: install
$ npm install
Core Api
setup
建立广播 📢 信道的前提是,需要使用
setup
进行初始化,建议在主应用合适的地方执行该方法一次即可
import { channel } from '@neural-nexus/portal-channel';
channel.setup()
on
监听
channel
消息,不管是来自于直接发送到channel
的还是转发到channel
的,返回一个移除监听器的句柄
import { channel } from '@neural-nexus/portal-channel';
const remove = channel.on('iframe-broadcast', (payload) => {
alert(`in qiankun: ${JSON.stringify(payload)}`)
// 移除监听器
remove()
})
⚠️ iframe 上下文里监听消息
由于
structured clone algorithm
的 🚫 限制,iframe 中监听的 callback 需要使用 cb.autoRun 进行包装
import { channel, cb } from '@neural-nexus/portal-channel';
// cb.autoRun 的魔法在于
// 1. 它突破了 structured clone algorithm 的限制
// 2. 将执行权转交至当前所在上下文
channel.on('qiankun-broadcast', cb.autoRun((payload) => {
alert(`in iframe: ${JSON.stringify(payload)}`)
}))
broadcast
向
channel
发送广播 📢 消息,channel
会向上下文发送特定消息
import { channel } from '@neural-nexus/portal-channel';
setTimeout(() => {
channel.broadcast('qiankun-broadcast', { key: 'hello, I am qianku.' })
}, 5000)
send
只向
channel
单向发送消息,通过send
发送到channel
的消息,可以在channel
监听,但是无法 📢 广播到其他上下文
import { channel } from '@neural-nexus/portal-channel';
channel.send(message, payload);
Enable Debug Mode
import { channel } from '@neural-nexus/portal-channel';
channel.debug();
和 iframe 握手通信
handshake
const disconnect = channel.handshake({
container: DOM_NODE,
url: IFRAME_URL,
name: NAME, // required, 必须声明
classListArray: [], // 你可以自行添加的 classList
});
// 请在合适的地方断开握手,释放连接
disconnect();
0.0.1
12 months ago