Last active
January 7, 2020 12:25
-
-
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
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
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