https://github.com/zignis/gist-iframe
Embed GitHub Gists to your website using iFrames, with proper height
https://github.com/zignis/gist-iframe
gist iframe
Last synced: 9 months ago
JSON representation
Embed GitHub Gists to your website using iFrames, with proper height
- Host: GitHub
- URL: https://github.com/zignis/gist-iframe
- Owner: zignis
- License: apache-2.0
- Created: 2022-01-03T14:59:51.000Z (over 4 years ago)
- Default Branch: main
- Last Pushed: 2022-09-14T12:46:32.000Z (almost 4 years ago)
- Last Synced: 2025-03-10T05:34:23.265Z (over 1 year ago)
- Topics: gist, iframe
- Language: JavaScript
- Homepage:
- Size: 13.7 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# gist-iframe


Uses the `postMessage` method to set the height of the iframe dynamically.
## ⚙️ Terminology
- 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.
## 🪱 Regex
We construct a RegExp to extract the `username` and `Gist ID` from the URL.
### Gist URL structure
```
https://gist.github.com/username/gistId
```
### RegExp
```
/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
```
## ✏️ Rendering the Gist
We render the Gist on the same origin, refer to [this file](https://github.com/HexM7/gist-iframe/blob/main/api/gist/%5B...slug%5D/index.js).
## 💻 The Font-end
We use the `useEffect` React hook to set the iframe's height once we receive it from our API route.
```ts
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);
}
}, []);
```
## :link: Links
- [GitHub Gist](https://gist.github.com/)
- [Next.js](https://nextjs.org/)
- [React](https://reactjs.org/)
- [postMessage API](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage)
## :ledger: License
[Apache License 2.0](https://github.com/HexM7/gist-iframe/blob/main/LICENSE)