🌳 Tiny & elegant & better windows post message,simple bnd powerful.
![Npm Example](https://private-user-images.githubusercontent.com/50035229/343014858-b2258dc9-2dc7-4f11-bf9d-d4e76855becd.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3MjE5MDgxODgsIm5iZiI6MTcyMTkwNzg4OCwicGF0aCI6Ii81MDAzNTIyOS8zNDMwMTQ4NTgtYjIyNThkYzktMmRjNy00ZjExLWJmOWQtZDRlNzY4NTViZWNkLnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNDA3MjUlMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjQwNzI1VDExNDQ0OFomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPTdhNTdiMGRhYTk3YzViYmNmMmM4ZTY2ZDI3NzBlNTQwZTVmN2ZmZDYwZmQwNjg1NzRhMDJjNjIwYjg4MzZlNWQmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0JmFjdG9yX2lkPTAma2V5X2lkPTAmcmVwb19pZD0wIn0.wOGsocj6d5Ws5UYuZEeKAzPjNxsPwzaljUv-gwN4FNY)
pnpm install next-post-message
Sending messages has never been easier:
import { Npm } from 'next-post-message'
const tgtWin = document.getElementById('iframeB').contentWindow
const npm = new Npm({ channel: '/chat' })
const { answer } = npm.post('Hello!', tgtWin)
answer
.then(res => console.log('Received:', res))
.catch(err => console.error('Error:', err))
In the receiver window, set up a handler to receive messages and send responses:
import { Npm } from 'next-post-message'
const npm = new Npm({ channel: '/chat' })
npm.onReceive(async (msg) => {
console.log('Received :', msg)
return 'Hello back'
})
Let's be honest, specifying the target window every time you send a message can get tedious.
That's where the PostMan
class comes in. It helps manage message sending with custom options and a pre-specified target window.
import { Npm } from 'next-post-message'
const tgtWin = document.getElementById('iframeB').contentWindow
const npm = new Npm({ channel: '/detail/blog' })
const postMan = npm.createPostMan(tgtWin, {
maxWaitTime: 20000,
enableDebug: true
})
const { answer: answer1 } = postMan.post('Hello through PostMan')
const { answer: answer2 } = postMan.post('Hello again through PostMan')
import { Npm } from 'next-post-message'
const npm = new Npm({ channel: '/detail/blog', enableDebug: true })
npm.onReceive(async (msg) => {
console.log('Received in:', message)
return 'Hello back'
})
Using Multiple GetMan
Instances for Listening Different Channels
import { Npm } from 'next-post-message'
const npm = new Npm({ enableDebug: true })
const getMan = npm.createGetMan({ channel: '/chat' })
getMan.onReceive(msg => console.log('Chat:', msg))
const getMan2 = npm.createGetMan({ channel: '/update' })
getMan2.onReceive(msg => console.log('Update:', msg))
Hope these examples help you get started quickly and make the most of NextPostMessage
!
MIT License © 2023-PRESENT leizhenpeng