Skip to content

Instantly share code, notes, and snippets.

@usefulthink
Last active October 1, 2017 23:05
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 usefulthink/d86fb057c26f93ebab7294f10e0ef43e to your computer and use it in GitHub Desktop.
Save usefulthink/d86fb057c26f93ebab7294f10e0ef43e to your computer and use it in GitHub Desktop.
opens any three.js example in codepen to play around with it.
function extractScriptContent(root) {
return Array.from(root.querySelectorAll('script:not([src])'))
.filter(el => !el.type || el.type.endsWith('javascript'))
.reduce((result, el) => {
el.parentNode.removeChild(el);
return result + el.textContent;
}, '');
}
function extractCssContent(root) {
return Array.from(root.querySelectorAll('style')).reduce((result, el) => {
el.parentNode.removeChild(el);
return result + el.textContent;
}, '');
}
function normalizeUrls(documentText) {
const normalizeUrl = (() => {
const urlHelper = document.createElement('a');
return url => {
urlHelper.href = url;
return urlHelper.toString();
};
})();
return documentText
.replace(
/(href|src)=(?:"([^"]*)"|'([^']*)')/g,
($0, attrName, dqValue, sqValue) =>
`${attrName}="${normalizeUrl(sqValue || dqValue)}"`
)
.replace(
/(\.\s*load\s*\(\s*')([^']*)(')/g,
($0, prefix, url, suffix) => prefix + normalizeUrl(url) + suffix
);
}
async function loadExampleHtml() {
let url = '';
if (document.location.pathname === '/examples/') {
url = document.location.hash.slice(1) + '.html';
}
return (await fetch(url)).text();
}
async function main() {
const text = await loadExampleHtml();
const parser = new DOMParser();
const doc = parser.parseFromString(normalizeUrls(text), 'text/html');
const js = extractScriptContent(doc);
const css = extractCssContent(doc);
const html = doc.body.innerHTML;
const form = document.createElement('form');
const input = document.createElement('input');
input.type = 'hidden';
input.name = 'data';
input.value = JSON.stringify({html, css, js});
form.appendChild(input);
form.method = 'POST';
form.action = 'https://codepen.io/pen/define';
document.body.appendChild(form);
form.submit();
}
main().catch(err => console.error(err));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment