README
@saryz/portal-bridge
用于iframe双向通信的封装
未来计划
返回promise以便可以在 async/await 时使用使代码逻辑更清晰
安装 install
npm i @saryz/portal-bridge -S
快速使用 Quick to use
监听 listen
import { PortalReceive } from "@saryz/portal-bridge"
// key 为子父约定
PortalReceive.listen(key, ({ data }) => {
// do something
})
触发 trigger
子->父 postToParent(子触发父方法)
import { PortalSend } from "@saryz/portal-bridge"
const params = { ... }
// key 为子父约定
PortalSend.postToParent(key, params)
父->子 postToIframe(父触发子方法)
import { PortalSend } from "@saryz/portal-bridge"
const params = { ... }
// iframe:HTMLIFrameElement
// const iframe = this.$refs.iframe // Vue
// const iframe = document.getElementById('iframe') // js
PortalSend.postToIframe(iframe, key, params)
回调 callback
获取父页面数据 Get the parent page data
/**** parent.js ****/
const key = 'getUserInfo'
const iframe = this.$refs.iframe
const params = { name: 'saryz', ... }
PortalReceive.listen(key, (data) => {
console.log('Received data from iframe', data)
PortalSend.postToIframe(iframe, key, params)
})
/**** child.js * example vue ****/
methods: {
// get the parent page data 获取父页面数据
getUserInfo()
{
const params = { msg: 'Please give me the user information' }
const key = 'getUserInfo'
PortalSend.postToParent(key, params, (data) => {
console.log('parent page data', data)
// do something
})
}
}
获取子页面数据 Get the child page data
/**** child.js ****/
const key = 'submit'
const params = { name: 'saryz', ... }
PortalReceive.listen(key, (data) => {
console.log('father need me', data)
// do something or What also not stem
PortalSend.postToParent(key, params )
})
/**** father.js * example vue ****/
methods: {
// get the parent page data 获取父页面数据
submit()
{
const params = { msg: 'Mahler gobi submit!' }
const key = 'submit'
const iframe = this.$refs.iframe
PortalSend.postToIframe(iframe, key, params, ({data}) => {
console.log('child data', data) // { name: 'saryz', ... }
// do something
})
}
}
接口 interface
/**
* 监听
*/
listen(methodName: string, callback: PortalBridgeCallback): void;
/**
* 发消息给iframe中的子页面
* @param iframe 必填,iframe对应的dom
* @param methodName 必填,通信名
* @param data 非必填,要传输的数据
* @param callback 非必填,通信回调,用于直接接收子级返回数据
*/
postToIframe(iframe: HTMLIFrameElement, methodName: string, data?: any, callback?: PortalBridgeCallback | undefined): void;
/**
* 发消息给父级页面
* @param methodName 必填,通信名
* @param data 非必填,要传输的数据
* @param callback 非必填,通信回调,用于直接接收父级返回数据
*/
postToParent(methodName: string, data?: any, callback?: PortalBridgeCallback | undefined): void;