Search code examples
javascriptvisual-studio-codemarkdownpreview

Can I run javascript in VS Code markdown preview?


Question: Can I get VS Code to execute JS in it's markdown preview.

A little background:

I like to use markdown in VS Code for taking notes, with a nice live preview happening in a pane to the side. I specifically like to make tables in it, but the formatting can get out of hand very quickly if you have even a minor amount of text in a certain column, especially if you use prettier.

I had the brain wave to just make a js variable with the text I'd like to include, and use document.write() to drop the text into the table, but keep the formatting in VScode from sprawling across lines. Lets pretend that I aliased document.write() to dw()

|<script>dw(colHeader1)</script>     |<script>dw(colHeader1)</script>           |
|------------------------------------|------------------------------------------|
|<script>dw(row1Col1Content)</script>|<script>dw(row1Col2Content)</script>      |

(Not the best example, might not be readable on mobile, but hopefully you get it).

Problem is, VScode doesn't run JS in it's preview window. Any way to make it do that?

Open to other suggestions on good ways to put large chunks of text into a table cell in markdown without the text formatting breaking to the point where it's more or less not human readable.


Solution

  • Yes VS Code's built-in markdown preview can run scripts, however scripts are disabled by default for security reasons. You can use the Markdown: Change preview security settings command to allow scripts:

    Working example of scripts in preview

    PS: But also note that just because you can, that doesn't mean you should