markdownclient-sidegisthtml-renderingjavascript-marked

Display GitHub Gist while rendering Markdown client-side


How can one display the contents of a GitHub Gist while parsing a markdown file client-side using Marked.js or with any other client Markdown library? The code below renders the Markdown file except the Gist.

fetch("https://raw.githubusercontent.com/Ayanmullick/test/master/testfolder/StachExgMdScript.md")
    .then(response => response.blob())  // Unwrap to a blob...
    .then(blob => blob.text())          // ...then to raw text...
    .then(markdown => {        // .pass raw text into marked.parse
document.getElementById("content").innerHTML=marked.parse(markdown)
    })
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>

<div id="content"></div>

However, the Gist renders OK in Visual Studio Code after disabling Markdown content preview settings : Disable preview security warning in this workspace.

enter image description here


Solution

  • One needs additional JavaScript to run the script tag while rendering Markdown client side.

    document.addEventListener("DOMContentLoaded", function() {
        fetch("https://raw.githubusercontent.com/Ayanmullick/test/master/testfolder/StachExgMdScript.md")
            .then((response) => response.text()) // Unwrap to a blob...
            .then((markdown) => {
                document.getElementById("content").innerHTML = marked.parse(markdown);
                var scriptTags = document.querySelectorAll("#content script");
                function handleDocumentWrite(content) {
                    var contentPlaceholder = document.getElementById("content");
                    contentPlaceholder.innerHTML += content}
                window.document.write = handleDocumentWrite;
                scriptTags.forEach(function(scriptTag) {
                    if (scriptTag.src) {
                        var externalScript = document.createElement("script");
                        externalScript.src = scriptTag.src;
                        document.getElementById("content").appendChild(externalScript);
                    } else {eval(scriptTag.innerText); }
                });
            });
    });
    <div id="content"></div>
     <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>