Hook for listening to window message event and posting message back to source
npm install @rottitime/react-hook-message-eventReact hook to monitor messages incoming and also allow you to post out.
Utilising and simplifing the WebAPI for Window.postMessage() and Window: message event
```
npm i @rottitime/react-hook-message-event
The two functionalities of this this hook.
1. Listening for messages from other windows or frames
2. Send a message to parent window/iframe
Just ensure you first import your hook into your component.
`js`
import useMessage from '@rottitime/react-hook-message-event'
The hook takes usage of the Window: message event to allow a component to listen for messages from other windows, iframes or tabs
The hook useMessage takes two arguments. The first is the name of the event you want to listen to. The second is a optional callback which can be fired once a message has been recieved
The callback provides two arguments. As per the example below
1. send can be used to ping a message back to the sourcepayload
2. gives you the data that was sent by the source
`js
const ExampleComponent = () => {
//Listen for the message 'authenticate' and then fire a callback
useMessage('authenticate', (send, payload) => {
console.log('I just received : ', payload)
//send back to sender a boolean payload
send({ type: 'authenticate', payload: { success: true } })
})
return
$3
The hook also takes usage of the Window.postMessage() to allow you to post messages to the parent window/tab/iframe.
In the example below, we are sending the message 'Hellow world' to the parent window
`js
const ExampleComponent = () => {
//Listen for the message 'authenticate' and then fire a callback
const { sendToParent } = useMessage('authenticate')
sendToParent({ type: 'authenticate', payload: { messahe: 'hello world' } })
return Hello world
}
``