Last active
October 6, 2019 10:58
-
-
Save ebachter/7460d22fff27566ebe50981cda01a7e2 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', '*'); | |
}; | |
window.addEventListener("message", this.handleFrameTasks); | |
} | |
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
Indeed, window.addEventListener was missing. Updated the code.