Skip to content

Instantly share code, notes, and snippets.

@bensampaio
Last active January 7, 2020 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bensampaio/73b2103422596b62de8f7c1abf300d53 to your computer and use it in GitHub Desktop.
Save bensampaio/73b2103422596b62de8f7c1abf300d53 to your computer and use it in GitHub Desktop.
Example of an iframe component that intercepts form submissions (with bugs)
class IFrame extends PureComponent {
constructor(props) {
super(props);
this.iframeElement = React.createRef();
this.state = {
location: props.location,
};
this.handleLoad = this.handleLoad.bind(this);
}
componentDidUpdate(prevProps, prevState) {
const { location: nextLocation } = this.props;
const iframeLocation = this.iframeElement.current.contentWindow.location;
const { pathname: nextPathname, search: nextSearch } = nextLocation;
const { pathname: iframePathname, search: iframeSearch } = iframeLocation;
if (iframePathname !== nextPathname || iframeSearch !== nextSearch) {
this.setState({ location: nextLocation });
}
}
// ...
handleLoad() {
const { history } = this.props;
const { location } = this.state;
const iframeLocation = this.iframeElement.current.contentWindow.location;
const { hash: currentHash, pathname: currentPathname, search: currentSearch } = location;
const { hash: iframeHash, pathname: iframePathname, search: iframeSearch } = iframeLocation;
// …
if (iframeHash !== currentHash || iframePathname !== currentPathname || iframeSearch !== currentSearch) {
history.push({
hash: iframeHash,
pathname: iframePathname,
search: iframeSearch,
});
}
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment