Skip to content

Instantly share code, notes, and snippets.

@ebachter
Last active October 6, 2019 10:58
Show Gist options
  • Save ebachter/7460d22fff27566ebe50981cda01a7e2 to your computer and use it in GitHub Desktop.
Save ebachter/7460d22fff27566ebe50981cda01a7e2 to your computer and use it in GitHub Desktop.
iframe handling in react
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;
@gtabmx
Copy link

gtabmx commented Apr 12, 2017

I believe you are missing window.addEventListener("message", this.handleFrameTasks); in your componentDidMount()

@ianbeks
Copy link

ianbeks commented Jun 7, 2018

I'm trying to detect url hash changes from the iframe in my app and failing dismally. any tips?

@jeremyquinton
Copy link

@gtabmx I think your right would be useful if that was in the gist as it confused me slightly. wondering if @ebakhtarov could update this really helped me thanks very much.

@ebachter
Copy link
Author

Indeed, window.addEventListener was missing. Updated the code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment