on
Rendering ChatGPT HTML Output Inline
TL;DR: With a little bit of glue, you can render and evaluate ChatGPT’s raw HTML and JavaScript output directly in the chat interface!!
While playing with ChatGPT, I found myself wanting to see its output.
ChatGPT can create HTML code, and it functions within a web browser. Since the browser is able to display HTML, is it possible to use it to display ChatGPT’s output?
Indeed, with just a bit of glue code we can see and interact with the output!
Here is some JS that, when evaluated, will render ChatGPT’s output (and yeah, ChatGPT helped me write this). Note I only tested this in Firefox.
function replaceLastCodeBlock() {
var codeBlocks = document.getElementsByTagName("code");
var lastCodeBlock = codeBlocks[codeBlocks.length - 1];
if (!lastCodeBlock) {
return;
}
var htmlContent = lastCodeBlock.innerText;
var fragment = document.createRange().createContextualFragment(htmlContent);
lastCodeBlock.parentNode.replaceChild(fragment, lastCodeBlock);
var elements = document.getElementsByClassName("bg-black");
for (var i = 0; i < elements.length; i++) {
elements[i].classList.remove("bg-black");
}
}
replaceLastCodeBlock();
Disclaimer: It’s probably not super secure to haphazardly evaluate code produced by a machine learning model; use at your own risk.
Let’s see some examples…
Here’s a simple showcase. The script above makes the browser render ChatGPT’s output.
CSS and JavaScript are evaluated.
ChatGPT can produce SVG code, which also can be rendered.
beautiful
Obligatory recursive ChatGPT in an iframe.
You can make the script feed input back into ChatGPT.
And data can be fetch
ed from the internet.
Combining data retrieval and feedback, you can jury-rig more advanced prompting with context. This is pretty brittle, and notice it erroneously outputs its knowledge cutoff year.
Animations can be rendered
A fun Game
ChatGPT’s ability to generate correct code is impressive in its own right. Being able to easily see and interact with the evalated artifacts of that textual output makes the tool more fun. Hopefully this little demo is thought-provoking, enjoy!