Created
March 21, 2019 13:28
-
-
Save neevai/743b48e5390c46b615833cc08ee3c179 to your computer and use it in GitHub Desktop.
React iframe component that listens to messages from the embedded document
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import PropTypes from 'prop-types'; | |
export default class ReactiveIframe extends React.Component { | |
static propTypes = { | |
origin: PropTypes.string.isRequired, | |
src: PropTypes.string.isRequired, | |
onMessage: PropTypes.func.isRequired, | |
title: PropTypes.string, | |
frameBorder: PropTypes.number | |
}; | |
static defaultProps = { | |
title: 'reactiveIframe', | |
frameBorder: 0 | |
}; | |
constructor(props) { | |
super(props); | |
this.handleMessage = this.handleMessage.bind(this); | |
} | |
componentDidMount = () => window.addEventListener('message', this.handleMessage); | |
componentWillUnmount = () => window.removeEventListener('message', this.handleMessage); | |
handleMessage = (messageEvent) => !~messageEvent.origin.indexOf(this.props.origin) ? null : this.props.onMessage(messageEvent.data); | |
render = () => <iframe title={this.props.title} src={this.props.src} frameBorder={this.props.frameBorder}/> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment