Skip to content

Instantly share code, notes, and snippets.

@bensampaio
Last active January 7, 2020 12:24
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/00f9dcd911f871474a228f7f41c2e62e to your computer and use it in GitHub Desktop.
Save bensampaio/00f9dcd911f871474a228f7f41c2e62e to your computer and use it in GitHub Desktop.
Example of an iframe component method that intercepts click, focus and mouse 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('focus mouseover', selector, (event) => {
const anchorElement = event.currentTarget;
const { hash, hostname, protocol, search } = anchorElement;
if (protocol === 'javascript:') {
return;
}
const route = history.createHref({
hash,
pathname: pathname.replace('/_content/', '/'),
search,
});
if (hostname === window.location.hostname) {
anchorElement.setAttribute('href', route);
} else {
anchorElement.setAttribute('href', protocol + '//' + hostname + route);
}
// Set the anchor hostname because this property is lost in IE after resetting the href but it is still necessary for the click event
// @see https://stackoverflow.com/questions/10755943/ie-forgets-an-a-tags-hostname-after-changing-href
anchorElement.hostname = hostname;
})
.on('click', selector, (event) => {
const anchorElement = event.currentTarget;
const { hash, hostname, href, pathname, protocol, search } = anchorElement;
if (protocol === 'javascript:') {
return;
}
if (event.ctrlKey || event.metaKey || event.shiftKey || (event.button && event.button === 1)) {
return;
}
event.preventDefault();
if (hostname === window.location.hostname) {
const route = history.createHref({
hash,
pathname,
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