UNPKG

iframe-channel

Version:

A channel used to communicate between iframe and parent. Support post function.

34 lines (30 loc) 927 B
import React, { useEffect, useState } from 'react' import Channel from 'iframe-channel' import { targetOrigin } from './constants' export default function ParentRequest () { const [message, setMessage] = useState(''); useEffect(() => { const channel = new Channel({ targetOrigin, // only accept targetOrigin's message target: window.parent // parent window }) channel.subscribe('xx', (data, message, event) => { // data === 'hello' // message == { type: 'xx', data: 'hello' } setMessage(data) return `${data}_hi` }) channel.connect() return () => { // destroy channel // Each Channel instance will add 'message' and 'beforeunload' event listener to window // object. So make sure destroy the instance once it's unused. channel && channel.destroy() } }, []) return ( <h3> Message from parent: {message} </h3> ) }