Skip to content

Instantly share code, notes, and snippets.

@ghengeveld
Created July 7, 2021 09:28
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 ghengeveld/cbd519b6a1a7e1ad778fec6d04d2729a to your computer and use it in GitHub Desktop.
Save ghengeveld/cbd519b6a1a7e1ad778fec6d04d2729a to your computer and use it in GitHub Desktop.
Storybook embed util
window.addEventListener("message", (message) => {
try {
const data = JSON.parse(message.data)
if (!data || data.context !== "iframe.resize") return
const url = new URL(data.src)
for (const key of [...url.searchParams.keys()]) {
if (!["path", "id", "args"].includes(key)) url.searchParams.delete(key)
}
for (const el of document.querySelectorAll(`iframe[src^="${url.href}"]`)) {
el.style.height = `${data.height}px`
}
} catch (e) {}
}, false)
document.addEventListener("DOMContentLoaded", () => {
for (const el of document.querySelectorAll("[storybook-embed]")) {
const storyUrl = new URL(el.getAttribute("storybook-embed"))
const oembedUrl = new URL(
`/oembed?url=${encodeURIComponent(storyUrl)}&format=json`,
`https://${storyUrl.host.replace(/^[^.]+/, "www")}`
)
fetch(oembedUrl)
.then((res) => res.json())
.then((data) => {
el.setAttribute('title', data.title)
el.style.height = `${data.height}px`
el.innerHTML = data.html
})
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment