Skip to content

Instantly share code, notes, and snippets.

@muratcorlu
Last active January 16, 2023 08:38
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 muratcorlu/e05cb2f37e31b8bde385181947d25a77 to your computer and use it in GitHub Desktop.
Save muratcorlu/e05cb2f37e31b8bde385181947d25a77 to your computer and use it in GitHub Desktop.
Custom Element Serializer

Getting an HTML snapshot of current DOM including Custom Elements

This is an attempt to get HTML snapshot of current document in browser to report current state to server, to get a screenshot on the server without running JS

function renderToString(element) {
if (!element.shadowRoot) {
return element.outerHTML;
}
const elementAdoptedStyles = element.shadowRoot.adoptedStyleSheets?.map((style) => {
let cssText = [];
for (const rule of style.cssRules) {
cssText.push(rule.cssText);
}
return cssText.join('');
});
return element.outerHTML.replace(
element.innerHTML,
`<template shadowroot="open">${
element.shadowRoot.innerHTML
}${ elementAdoptedStyles ? `<style>${elementAdoptedStyles}</style>` : '' }</template>${element.innerHTML}`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment