IVAN STANTON

Computer Nerd

Code Snippet: Rendering Markdown pages as HTML

I haven't done any Javascript on this site yet. That's because I'm not very experienced with Javascript. Still, I know my way around it.

I put together a quick code snippet to render a page formatted in Markdown as HTML. There's a library called Marked.js which is usually used with Node.js, but can also be used entirely clientside. It includes a function called marked(string) which takes a Markdown-formatted string and outputs an HTML-formatted string.

We'll use it along with the (usually built in) XMLHttpRequest function to create a useful utlity, which prompts for a Markdown-formatted page and displays it as HTML.

The result (plus my website's style) is here. I hope it is useful to you.

<!doctype html>
<html>
<head>
  <meta charset="utf-8"/>
  <title>Markdown page viewer</title>
</head>
<body>
<!doctype html>
<html>
<head>
  <meta charset="utf-8"/>
  <title>Markdown page viewer</title>
</head>
<body>
  <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
  <script>
    function loadpage(url)
    {
        if (window.XMLHttpRequest)
        {
            request=new XMLHttpRequest();
        }
        else
        {
            request=new ActiveXObject("Microsoft.XMLHTTP");
        }
        request.onreadystatechange=function()
        {
            if (request.readyState==4 && request.status==200)
            {
                document.write(marked(request.responseText));
            }
        }
        request.open("GET", url, false);
        request.send();
    }
    loadpage(prompt("Location of Markdown"))
  </script>
</body>
</html>  <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
  <script>
    function pageload(theURL)
    {
        if (window.XMLHttpRequest)
        {// Using XMLHttpRequest
            response=new XMLHttpRequest();
        }
        else
        { // Using ActiveXObject
            response=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function()
        {
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                document.write(marked(response.responseText));
            }
        }
        response.open("GET", theURL, false);
        xmlhttp.send();
    }
    loadXMLDoc(prompt("Location of Markdown"))
  </script>
</body>
</html>