Uses the postMessage
method to set the height of the iframe dynamically.
- Renders a Gist on the
/api/gist
API route to aid same-origin policy. - The API route uses
window.postMessage()
API to send the height of the Gist to the front-end dynamically. - THe iframe's height is received on the front-end.
We construct a RegExp to extract the username
and Gist ID
from the URL.
https://gist.github.com/username/gistId
/https?:\/\/gist\.github\.com\/([^\/\?\&]*\/[^\/\?\&]*)/
We use the group catched from the above RegExp and use our API route to render the Gist on the same origin.
/api/gist/username/gistId
We render the Gist on the same origin, refer to this file.
We use the useEffect
React hook to set the iframe's height once we receive it from our API route.
React.useEffect(() => {
function receiveMessage(event: MessageEvent): void {
const frames = document.getElementsByTagName('iframe');
for (let i = 0; i < frames.length; i += 1) {
if (frames[i].contentWindow === event.source) {
if (event.data && event.data.height) {
frames[i].style.height = event.data.height;
}
}
}
}
window.addEventListener('message', receiveMessage, false);
return = () => {
window.removeEventListener('message', receiveMessage, false);
}
}, []);