Skip to content

Instantly share code, notes, and snippets.

@lepture
Created May 12, 2022 13:26
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 lepture/8237251d19d53a8e6627514d1b0104de to your computer and use it in GitHub Desktop.
Save lepture/8237251d19d53a8e6627514d1b0104de to your computer and use it in GitHub Desktop.
Gist in Shadow DOM, for react, vue, svetle, and etc.
const iframeCode = `
<style>html,body{margin:0;padding:0}</style>
<script>
window.addEventListener("message", (e) => {
if (e.ports) {
const channel = e.ports[0]
const timestamp = e.data.init
channel.postMessage({'height': document.body.scrollHeight, 'timestamp': timestamp})
}
})
</script>
`
customElements.define('github-gist', class extends HTMLElement {
connectedCallback() {
const shadow = this.attachShadow({mode: 'open'})
const channel = new MessageChannel()
const iframe = document.createElement('iframe')
const timestamp = Date.now()
iframe.setAttribute('frameborder', '0')
iframe.setAttribute('width', '100%')
iframe.addEventListener('load', () => {
iframe.contentWindow.postMessage({'init': timestamp}, '*', [channel.port2])
})
channel.port1.onmessage = (event) => {
if (timestamp == event.data.timestamp) {
iframe.style.height = event.data.height + 20 + 'px'
}
}
const path = this.getAttribute('path')
iframe.srcdoc = `<script src="https://gist.github.com/${path}.js"></script>` + iframeCode
shadow.appendChild(iframe)
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment