Skip to content

Instantly share code, notes, and snippets.

@bensampaio
Last active January 7, 2020 12:25
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/1a5b76e3ebaf1fff4868f1a34591ccb3 to your computer and use it in GitHub Desktop.
Save bensampaio/1a5b76e3ebaf1fff4868f1a34591ccb3 to your computer and use it in GitHub Desktop.
Example of an iframe component method that intercepts click events on anchor elements
class IFrame extends PureComponent {
// ...
bindEventsToAnchorsInIFrame(iframeElement) {
const { history, location } = this.props;
const { contentDocument, contentWindow } = iframeElement;
const { jQuery } = contentWindow;
const selector = 'a[href]:not([download]):not([target=_blank])';
jQuery(contentDocument)
.on('click', selector, (event) => {
const anchorElement = event.currentTarget;
const { hash, hostname, href, pathname, protocol, search } = anchorElement;
if (protocol === 'javascript:') {
return;
}
event.preventDefault();
if (hostname === window.location.hostname) {
const route = history.createHref({
hash,
pathname: pathname.replace('/_content/', '/'),
search,
});
history.push(route);
} else {
window.location.assign(href);
}
});
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment