5

One can follow the Marked library documentation and render a Markdown string inline. This is a working code snippet.

<div id="content"></div>
  <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
  <script>
    document.getElementById('content').innerHTML =
      marked.parse('# Hello Ayan \n\nRendered by **marked**.');
  </script>

Is there a way to pass a file into the marked.parse function or through any other client-side Markdown rendering library and render the whole file instead of just a string? I looked into getting the markdown file and passing it as a string. However, I couldn't find a straightforward way.

The file is in the same folder as this HTML file and would be served from GitHub using GitHub Pages. However, I could use an absolute link from a CDN if needed. How would I pass the contents to marked.parse()? marked.parse(Hello.md) didn't work.

2
  • 1
    Where would the file come from? Client-side JavaScript doesn't have any way to access the user's filesystem. And if the file is available via HTTP or similar, just retrieve it and pass its contents into marked.parse(). Commented Nov 29, 2021 at 18:03
  • The file is in the same folder as this HTML file and would be served from GitHub using GitHub Pages. However, I could use an absolute link from a CDN if needed. How would I pass the contents to marked.parse()? marked.parse(Hello.md) didn't work. Commented Nov 29, 2021 at 18:09

1 Answer 1

10
+150

The file is in the same folder as this HTML file and would be served from GitHub using GitHub Pages

You can have the browser fetch the content and then pass its content to marked.parse(). Something like this should work:

<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script>
  fetch("/pages-site/markdown.md")      // The path to the raw Markdown file
    .then(response => response.blob())  // Unwrap to a blob...
    .then(blob => blob.text())          // ...then to raw text...
    .then(markdown => {                 // ...then pass the raw text into marked.parse
      document.getElementById("content").innerHTML = marked.parse(markdown);
    });
</script>

Here is a live example.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.