-
-
Save banhaclong20/d6b10c5f083b15783d688991aa1a9be8 to your computer and use it in GitHub Desktop.
iframe handling in react
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 { connect } from 'react-redux'; | |
class PageWidget extends React.Component { | |
componentDidMount() { | |
this.ifr.onload = () => { | |
this.ifr.contentWindow.postMessage('hello', '*'); | |
}; | |
} | |
componentWillReceiveProps(nextProps) { | |
for (const [objectid, liveData] of Object.entries(nextProps.objectsLive)) { | |
........ | |
const prevOn = this.props.objectsLive[objectid] ? this.props.objectsLive[objectid].on : null; | |
if (prevOn !== liveData.on) { | |
this.ifr.contentWindow.postMessage({ event: 'onoff', object: objectid, value: liveData.on }, '*'); | |
} | |
} | |
} | |
shouldComponentUpdate() { | |
return false; | |
} | |
componentWillUnmount() { | |
window.removeEventListener('message', this.handleFrameTasks); | |
} | |
sendToFrame(data) { | |
if(this.ifr) this.ifr.contentWindow.postMessage(data, '*'); | |
} | |
handleFrameTasks = (e) => { | |
if (e.data.type === 'bookmark') { | |
this.sendToFrame({ event: 'bookmark', data: window.location.hash ? window.location.hash.substr(1) : null }); | |
} | |
} | |
render() { | |
return ( | |
<div> | |
<iframe | |
sandbox="allow-scripts" | |
style={{ width: '100%' }} | |
src="https://iframe.com/" | |
ref={(f) => { this.ifr = f; }} | |
/> | |
</div> | |
); | |
} | |
} | |
export default PageWidget; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment