Created
May 12, 2022 13:26
-
-
Save lepture/8237251d19d53a8e6627514d1b0104de to your computer and use it in GitHub Desktop.
Gist in Shadow DOM, for react, vue, svetle, and etc.
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
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